package com.shensi.appCollect.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shensi.api.admin.domian.integral.dto.CustomerPointsRecord;
import com.shensi.api.order.domian.station.*;
import com.shensi.appCollect.constantEnum.Constant;
import com.shensi.appCollect.constantEnum.DecimalConstant;
import com.shensi.appCollect.constantEnum.integralTypeEnum;
import com.shensi.appCollect.dao.*;
import com.shensi.appCollect.enums.PayTypeEnum;
import com.shensi.appCollect.handle.PayOrderHandle;
import com.shensi.appCollect.param.request.PayInfoRequest;
import com.shensi.appCollect.param.request.PayOrderRequest;
import com.shensi.appCollect.param.request.PosUpdateOrderStatus;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.pojo.dto.DivideAccountsSettingDto;
import com.shensi.appCollect.service.*;
import com.shensi.appCollect.service.impl.ReductionActivityServiceImpl;
import com.shensi.appCollect.utils.*;
import com.shensi.appCollect.utils.exception.CustomException;
import com.shensi.appCollect.utils.exception.EndingException;
import com.shensi.appCollect.utils.jinkong.JKPayParam;
import com.shensi.appCollect.utils.jinkong.JKPayUtil;
import com.shensi.appCollect.utils.redis.RedisCacheUtil;
import com.shensi.appCollect.utils.sxfpay.SXFPayParam;
import com.shensi.appCollect.utils.sxfpay.SXFPayUtil;
import com.shensi.appCollect.utils.tonglianpay.SybConstants;
import com.shensi.appCollect.utils.tonglianpay.SybUtil;
import com.shensi.appCollect.utils.tonglianpay.TLPayParam;
import com.shensi.appCollect.utils.tonglianpay.TLPayUtil;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.TLFusClassPayUtil;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.struct.body.TLFusClassPayParam;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.util.SignUtils;
import com.shensi.appCollect.utils.weixinapp.WxPushUtil;
import com.shensi.appCollect.utils.weixinapp.WxTemplateData;
import com.shensi.appCollect.utils.weixinapp.WxTemplateMsg;
import com.shensi.appCollect.utils.yunHua.YunHuaParam;
import com.shensi.appCollect.utils.yunHua.yunHuaPayUtils;
import com.shensi.appCollect.utils.yunpay.SBPayParam;
import com.shensi.appCollect.utils.yunpay.SBPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/***
 * <Title> QuJiaPayController </Title>
 * <Description> 趣加 新版小程序订单 App生成订单，与调用第三方支付控制层 </Description>
 * <Date>2021年10月28日</Date>
 */

@RestController
@Api(tags = "趣加App支付")
//@QuJiaRequest()
@CrossOrigin
@Slf4j
public class QuJiaPayController {

    private static Logger logger = (Logger) LoggerFactory.getLogger(QuJiaPayController.class);

    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private PayOrderMapper payOrderMapper;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private IntegralRuleService integralRuleService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private ReductionActivityService reductionActivityService;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private CustomerPointsRecordService customerPointsRecordService;
    @Resource
    private PosMachineService posMachineService;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private AppUserSuperService appUserSuperService;
    @Resource
    private CouponService couponService;

    @Autowired
    private FleetCardService fleetCardService;

    @Autowired
    private FleetCardSubService fleetCardSubService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private OrderPayTypeService orderPayTypeService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${qujia.domainName}")
    private String domainName;
    @Value("${qujia.private_pfxPath}")
    private String private_pfxPath;

    @Value("${qujia.public_certPath}")
    private String public_certPath;

    @Value("${qujia.yunhuaPrePayUrl}")
    private String yunHuaPrePayUrl;

    @Value("${qujia.yunhuaPayUrl}")
    private String yunhuaPayUrl;
    @Autowired
    private CustomerCardSettingDetailService customerCardSettingDetailService;
    @Autowired
    private AppUserInfoMapper appUserInfoMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private AppUserSuperDetailMapper appUserSuperDetailMapper;
    @Autowired
    private AppUserSuperMapper appUserSuperMapper;

    @ApiOperation(value = "根据订单和选择的优惠券id以及立减活动id计算优惠", httpMethod = "POST", notes = "根据订单和选择的优惠券id以及立减活动id计算优惠")
    @PostMapping(value = "/calculateCouponAndActivity", produces = "application/json;charset=UTF-8")
    @Transactional
    public String calculateCouponAndActivity(@RequestBody PayOrder payOrderInfo) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        //获取该订单信息
        PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(payOrderInfo.getOrderNo());
        payOrder.setActivityId(payOrderInfo.getActivityId());
        payOrder.setDiscountCoupon(payOrderInfo.getDiscountCoupon());
        payOrder.setRulesId(payOrderInfo.getRulesId());
        payOrder = reductionActivityService.calculateCouponAndActivity(payOrder);
        resultData = ResultData.success(payOrder);
        return gson.toJson(resultData);
    }

    /*
     * 小程序创建加油支付订单
     * @param payOrderRequest
     * @return
     */
    @ApiOperation(value = "小程序创建加油支付订单", httpMethod = "POST", notes = "小程序创建加油支付订单")
    @PostMapping(value = "/createPayOrder", produces = "application/json;charset=UTF-8")
    @Transactional(rollbackFor = Exception.class)
    public String createPayOrder(@RequestBody PayOrderRequest payOrderRequest) {

        logger.info("/createPayOrder-" + payOrderRequest.getMobilePhone() + "--request:" + payOrderRequest.toString());
        // 新版本使用手机号，老版本使用openId
        ReductionActivity reductionActivity = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        AppUserInfo appUserInfo = new AppUserInfo();     //查询客户信息传递参数
        PayOrder payOrder = new PayOrder();             //生成订单参数
        if (StringUtils.isBlank(payOrderRequest.getUtmSource())) {
            // 订单来源默认9
            payOrderRequest.setUtmSource("9");
        }
        if (payOrderRequest.getStationId() != null
                && StringUtils.isNotBlank(payOrderRequest.getOrderOriginType())
                && StringUtils.isNotBlank(payOrderRequest.getGunName())
                && payOrderRequest.getReceivableAmt() != null) {
            if (StringUtils.isNotBlank(payOrderRequest.getVersion()) && "1".equals(payOrderRequest.getVersion())) {
                //创建订单新版本使用手机号
                appUserInfo.setMobilePhone(payOrderRequest.getMobilePhone());
                payOrder.setCustomerPhone(payOrderRequest.getMobilePhone());
            } else {
                switch (payOrderRequest.getPayType()) {
                    case "wx":        //小程序
                        appUserInfo.setMinaOpenid(payOrderRequest.getOpenId());
                        break;
                    case "zfb":       //支付宝
                        appUserInfo.setAliUserId(payOrderRequest.getAliUserId());
                        break;
                }
            }
            Station stationInfo = enterpriseService.selectStationById(payOrderRequest.getStationId());

            payOrder.setEnterpriseId(stationInfo.getEnterpriseId());
            payOrder.setEnterpriseName(stationInfo.getEnterprise().getEnterpriseName());
            payOrder.setUtmSource(payOrderRequest.getUtmSource());

            Map<String, Object> resultMap = new HashMap<>();            //返回结果集
            if (stationInfo != null) {
                if (StringUtils.isNotBlank(stationInfo.getEmployeeAppletFlag()) && "1".equals(stationInfo.getEmployeeAppletFlag()) && !StringUtils.isNotBlank(payOrderRequest.getUserId())) {
                    //是否启用  必须扫加油员扫码
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return gson.toJson(ResultData.error(CodeMsg.SCAN_EMPLOYEE));
                } else {
                    payOrder.setOrderRandomId(payOrderRequest.getOrderRandomId());


                    // payOrder 初始赋值

                    payOrder.setAppType(payOrderRequest.getAppType());
                    payOrder.setPayType(payOrderRequest.getPayType());
                    payOrder.setOrderOriginType(payOrderRequest.getOrderOriginType());
                    payOrder.setStationName(stationInfo.getStationName());

                    appUserInfo.setStationId(stationInfo.getEnterpriseId());
                    AppUserInfo appUserInfos = appUserInfoService.getAppUserInfo(appUserInfo);


                    // resultData 初始赋值

                    //获取油站图片和名称
                    resultMap.put("stationName", stationInfo.getStationName());
                    //获取油站图片和名称
                    resultMap.put("stationPic", stationInfo.getHeadImg());


                    //---------------------


                    if (appUserInfos != null) {
                        payOrder.setConsumer(appUserInfos.getBlogNickName());                   //昵称
                        payOrder.setConsumerId(appUserInfos.getUserId());                       //用户id
                        payOrder.setOilPersonnelId(payOrderRequest.getUserId());                //加油员ID
                        Random random = new Random();
                        String result = "";
                        for (int i = 0; i < 6; i++) {
                            result += random.nextInt(10);
                        }
                        String ordNo = System.currentTimeMillis() + result;
                        logger.info("/createPayOrder-" + payOrderRequest.getMobilePhone() + "--ordNo:" + ordNo);
                        payOrder.setOrderNo(ordNo);                                          //订单号
                        payOrder.setStationId(payOrderRequest.getStationId());                  //油站id
                        payOrder.setStatus("0");                                                //创建订单 未支付状态 0
                        payOrder.setCreatedDate(new Timestamp(new Date().getTime()));           //创建时间
                        payOrder.setOilGun(payOrderRequest.getGunName());                        //油枪号
                        payOrder.setReceivableAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));      //订单应收金额
                        payOrder.setDzkAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));             //电子卡金额

                        //油品价格
                        StaOilGun staOilGun = new StaOilGun();
                        staOilGun.setGunName(payOrderRequest.getGunName());
                        staOilGun.setStationId(payOrderRequest.getStationId());
                        StaOilGun staOilGunInfo = enterpriseService.selectStaGunInfo(staOilGun);
                        BigDecimal oilStationPrice = staOilGunInfo.getOilStationPrice();
                        String oilPrice = oilStationPrice.toString();                    //油站油品价格
                        payOrder.setOilPirce(oilPrice);

                        payOrder.setOrderType(staOilGunInfo.getOil().getOilClass());        //订单类型

                        //油品名称
                        payOrder.setOilName(staOilGunInfo.getOilId().toString());
                        //实收金额
                        payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        //优惠金额
                        payOrder.setDiscountAmt(Double.valueOf("0.00"));
                        //加油升数
                        BigDecimal oilLiters = new BigDecimal(payOrderRequest.getReceivableAmt()).divide(new BigDecimal(oilPrice), 4, BigDecimal.ROUND_HALF_UP);
                        payOrder.setOrderLiters(oilLiters.toString());

                        //Enterprise enterprise = enterpriseService.selectEnterpriseInfo(stationInfo.getEnterpriseId());
                        resultMap.put("cardFlag", stationInfo.getEnterprise().getCardFlag());                //是否开启电子卡

                        //获取电子卡余额
                        if ("1".equals(stationInfo.getEnterprise().getCardFlag())) {
                            logger.info("/createPayOrder-" + payOrderRequest.getMobilePhone() + "--cardType:" + staOilGunInfo.getOil().getCardType());

                            CustomerElectronicCard customerElectronicCard = electronicMembershipCardService.getAndCreateCustomerElectronicCard(appUserInfos, staOilGunInfo.getOil().getCardType(), stationInfo);
                            resultMap.put("balance", customerElectronicCard.getTotalAmt());
                        }

                        // 检验随机码
                        PayOrder payOrderInfoByOrderRandomId = null;
                        if (StringUtils.isNotBlank(payOrderRequest.getOrderRandomId())) {
                            // 此处为了防止多次请求接口，插入了多个一样的OrderRandomId
                            List<PayOrder> payOrderInfoListByOrderRandomId = payOrderService.selectPosPayOrderListInfoByOrderRandomId(payOrderRequest.getOrderRandomId());
                            if (payOrderInfoListByOrderRandomId.size() != 0) {
                                payOrderInfoByOrderRandomId = payOrderInfoListByOrderRandomId.get(0);
                            }
                        }
                        if (payOrderInfoByOrderRandomId != null) {
                            logger.info("/createPayOrder-" + payOrderRequest.getMobilePhone() + "--重复随机码:" + payOrderRequest.getOrderRandomId());
                            //POS机扫码下订单根据随机数查询，如果有，则表示该二维码已被扫用；
                            Boolean flag = payOrderInfoByOrderRandomId.getCustomerPhone().equals(payOrderRequest.getMobilePhone())
                                    && payOrderInfoByOrderRandomId.getAppType().equals(payOrderRequest.getAppType())
                                    && payOrderInfoByOrderRandomId.getPayType().equals(payOrderRequest.getPayType())
                                    && payOrderInfoByOrderRandomId.getOrderOriginType().equals(payOrderRequest.getOrderOriginType())
                                    && payOrderInfoByOrderRandomId.getStationId().compareTo(payOrderRequest.getStationId()) == 0
                                    && payOrderInfoByOrderRandomId.getOilPersonnelId().equals(payOrderRequest.getUserId())
                                    && (new BigDecimal(payOrderInfoByOrderRandomId.getReceivableAmt())).setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(new BigDecimal(payOrderRequest.getReceivableAmt()).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0
                                    && "0".equals(payOrderInfoByOrderRandomId.getStatus());
                            if (flag) {
                                int delCount = payOrderMapper.delOldRandomId(payOrderRequest.getOrderRandomId());
                                if (delCount == 0) {
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return gson.toJson(ResultData.error(new CodeMsg(-8, "二维码已经被扫用")));
                                }
                            } else {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return gson.toJson(ResultData.error(CodeMsg.ALREADY_SCANCODE));
                            }

                        }


                        //判断是否插入成功，成功返回
                        String activityRule1 = null;
                        String activityRule2 = null;
                        PayOrderHandle.setPayOrderInvoiceStatus(payOrder);
                        if (payOrderMapper.insertSelective(payOrder) > 0) {
                            //计算优惠金额
//                                BigDecimal reductionAmount = reductionActivityService.selectReductionByPayOrder(appUserInfos, payOrder, "CSP", payOrderRequest);
                            Map<String, Object> amountMap
                                    = reductionActivityService.selectReductionByPayOrder(appUserInfos, payOrder, "CSP", payOrderRequest, stationInfo, staOilGun);
                            if (amountMap.get("activityRule") != null) {
                                activityRule1 = (String) amountMap.get("activityRule");
                            }
                            Map<String, Object> rCHResult = reductionActivityService.getRCHReductionAmt(appUserInfos, payOrder, payOrderRequest, stationInfo);
                            if (rCHResult.containsKey("reductionActivity")) {
                                reductionActivity = (ReductionActivity) rCHResult.get("reductionActivity");
                            }
                            if (amountMap.get("activityRule") != null) {
                                activityRule2 = (String) rCHResult.get("activityRule");
                            }

                            //记录 充值立减活动优惠金额、消费立减活动优惠金额
                            if (amountMap.get("reductionAmount") != null) {
                                payOrder.setConsumeDiscountAmt(new BigDecimal(amountMap.get("reductionAmount").toString()));
                            }
                            if (rCHResult.get("rCHReductionAmt") != null) {
                                payOrder.setRechargeDiscountAmt((BigDecimal) rCHResult.get("rCHReductionAmt"));
                            }

                            BigDecimal rCHReductionAmt = (BigDecimal) rCHResult.get("rCHReductionAmt");
                            List<CouponUser> couponList2 = (List<CouponUser>) rCHResult.get("couponList");


                            BigDecimal reductionAmount = BigDecimal.ZERO;
                            //多个立减活动，活动用途不同，则优惠相加
                            reductionAmount = reductionAmount.add(rCHReductionAmt);
                            if (amountMap != null && amountMap.containsKey("reductionAmount") && amountMap.get("reductionAmount") != null) {
                                reductionAmount = reductionAmount.add(new BigDecimal(amountMap.get("reductionAmount").toString()));
                                if ((new BigDecimal(payOrderRequest.getReceivableAmt()).subtract(reductionAmount)).compareTo(new BigDecimal("0.01")) <= 0) {
                                    reductionAmount = new BigDecimal(payOrderRequest.getReceivableAmt()).subtract(new BigDecimal("0.01"));
                                }
                            }
                            if (amountMap != null && amountMap.containsKey("couponList") && amountMap.get("couponList") != null) {
                                //可用的优惠券列表
                                List<CouponUser> couponList = (List<CouponUser>) amountMap.get("couponList");
                                Set<CouponUser> quchong = new HashSet<>();
                                quchong.addAll(couponList);
                                quchong.addAll(couponList2);
                                List<CouponUser> total = new ArrayList<>(quchong);
                                resultMap.put("couponList", total);
                            }
                            resultMap.put("couponEnabledFlag", stationInfo.getEnterprise().getCouponEnabledFlag());
                            //实收金额
                            BigDecimal amt = new BigDecimal(payOrderRequest.getReceivableAmt()).subtract(reductionAmount);
                            //油企是否开启优惠券功能
                            CouponUser couponUser = null;
                            if (null != stationInfo.getEnterprise().getCouponEnabledFlag() && "1".equals(stationInfo.getEnterprise().getCouponEnabledFlag())) {
                                Map<String, Object> p = new HashMap<>();
                                p.put("issueType", "3");
                                p.put("stationId", stationInfo.getStationId());
                                p.put("curTime", new Date());
                                //获取油企给当前油站设置的issueType=3时，消费完成后的可选择领取的优惠券活动;
                                List<CouponIssue> couponIssueInfo = couponService.selectCouponListByCouponIssueId(p);
                                if (null != couponIssueInfo && couponIssueInfo.size() >= 1) {
                                    resultMap.put("couponIssueInfo", couponIssueInfo.get(0).getCouponIssueId());
                                }
                                //选择活动力度最大的优惠券
                                couponUser = reductionActivityService.getDiscountMaxCoupon(amt, payOrder.getReceivableAmt().toString(), (List<CouponUser>) resultMap.get("couponList"), appUserInfos.getMobilePhone());
                                if (reductionActivity != null) {
                                    if (StringUtils.isNotEmpty(reductionActivity.getActivityRule()) && reductionActivity.getActivityRule().equals("2")) {
                                        couponUser = null;
                                    }
                                }
                                if (payOrderRequest.getPayType().equals("zfb")) {
                                    //排除支付宝
                                    couponUser = null;
                                }
                                if (activityRule1 == null && activityRule2 == null) {
                                    //可以选优惠力度最大的优惠券
                                } else if (activityRule1 == null && activityRule2 != null) {
                                    if (activityRule2.equals("2")) {
                                        couponUser = null;
                                    }
                                } else if (activityRule1 != null && activityRule2 == null) {
                                    if (activityRule1.equals("2")) {
                                        couponUser = null;
                                    }
                                } else {
                                    if (activityRule1.equals("2") && activityRule2.equals("2")) {
                                        couponUser = null;
                                    }
                                }
                            }
                            if (couponUser != null && couponUser.getFinalCouponAmount() != null) {
                                BigDecimal finalCouponAmount = couponUser.getFinalCouponAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
                                payOrder.setDiscountCouponAmt(finalCouponAmount.doubleValue());
                                payOrder.setCouponUserId(couponUser.getCouponUserId().toString());
                                payOrder.setDiscountCoupon(couponUser.getCouponUserId().toString());
                                amt = amt.subtract(finalCouponAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                                if (amt.compareTo(BigDecimal.ZERO) < 1) {
                                    amt = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
                                }
                                resultMap.put("discountCouponAmt", finalCouponAmount);
                                resultMap.put("discountCoupon", couponUser.getCouponUserId());
                                resultMap.put("discountMaxCoupon", couponUser);
                            }

                            payOrder.setDiscountAmt(reductionAmount.doubleValue());

                            payOrder.setAmt(amt.doubleValue());
                            payOrder.setDzkAmt(amt.doubleValue());

                            payOrderMapper.updateByPrimaryKeySelective(payOrder);
                            //优惠价格
                            BigDecimal discountPrice = amt.divide(oilLiters, 2, BigDecimal.ROUND_HALF_UP);
                            resultMap.put("discountPrice", discountPrice);                      //优惠价格
                            resultMap.put("discountAmt", reductionAmount);                      //优惠金额
                            resultMap.put("amt", amt);                                          //实收金额
                            resultMap.put("dzkAmt", amt);                                       //电子卡支付金额
                            resultMap.put("receivableAmt", payOrderRequest.getReceivableAmt()); //应收金额
                            resultMap.put("oilLiters", oilLiters);                              //加油升数
                            resultMap.put("ordNo", ordNo);                                      //订单号
                            resultMap.put("cardType", staOilGunInfo.getOil().getCardType());    //该油品对应的电子卡类型

                            logger.info("/createPayOrder-" + payOrderRequest.getMobilePhone() + "--返回前端的结果:" + resultMap.toString());
                            resultData = ResultData.success(resultMap);
                            return gson.toJson(resultData);
                        } else {//如果插入数据库失败，就直接返回失败
                            resultData = ResultData.error(CodeMsg.Network_Exception);
                        }
                    } else {
                        //登录人验证失败
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return gson.toJson(ResultData.error(CodeMsg.USER_NOT_EXSIST_TO_RELOAD));
                    }


                    //--------------------
                }
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return gson.toJson(ResultData.error(CodeMsg.STATION_NULL_INFO));
            }
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return gson.toJson(ResultData.error(CodeMsg.REQUEST_FAIL));
        }
        return gson.toJson(resultData);
    }


    private String generateOrdNo() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }

    private void checkOrderRandomId(PayOrderRequest request) throws EndingException {
        PayOrder duplicateOrder = payOrderService.selectPosPayOrderInfoByOrderRandomId(request.getOrderRandomId());
        if (duplicateOrder != null) {
            logger.info("/createOrder-" + request.getMobilePhone() + "--出现重复的随机码:" + duplicateOrder.getOrderRandomId());
            //POS机扫码下订单根据随机数查询，如果有，则表示该二维码已被扫用；
            Boolean flag = duplicateOrder.getCustomerPhone().equals(request.getMobilePhone())
                    && duplicateOrder.getAppType().equals(request.getAppType())
                    && duplicateOrder.getPayType().equals(request.getPayType())
                    && duplicateOrder.getOrderOriginType().equals(request.getOrderOriginType())
                    && duplicateOrder.getStationId() == request.getStationId()
                    && duplicateOrder.getOilPersonnelId().equals(request.getUserId())
                    && (new BigDecimal(duplicateOrder.getReceivableAmt())).setScale(2, BigDecimal.ROUND_HALF_UP).compareTo(new BigDecimal(request.getReceivableAmt()).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0
                    && "0".equals(duplicateOrder.getStatus());
            if (!flag) {
                // 前端根据8 来提示扫码
                throw new EndingException(-8, "二维码已经被扫用");
            }

            int delCount = payOrderMapper.delOldRandomId(request.getOrderRandomId());

            if (delCount == 0) {
                // 前端根据8 来提示扫码
                throw new EndingException(-8, "二维码已经被扫用");
            }

        }
    }

    //获取电子卡余额
//    public CustomerElectronicCard getCustomerElectronicCard(AppUserInfo appUserInfos, String cardType){
//        logger.info("查询用户电子卡参数：油站ID：" + appUserInfos.getStationId() + "卡类型：" + cardType + "手机号：" + appUserInfos.getMobilePhone());
//        CustomerElectronicCard electronicCardInfoByPhone
//                = electronicMembershipCardService.getElectronicCardInfoByPhone(CustomerElectronicCard.builder()
//                .stationId(appUserInfos.getStationId())
//                .cardOilsType(cardType)
//                .mobilePhone(appUserInfos.getMobilePhone()).build());
//        if(null != electronicCardInfoByPhone){
//            //存在
//            return electronicCardInfoByPhone;
//        }else {
//            //不存在
//            CustomerElectronicCard ces = new CustomerElectronicCard();
//            ces.setCreateTime(new Date());
//            ces.setAmt(BigDecimal.ZERO);
//            ces.setCardOilsType(cardType);
//            ces.setCustomerNo(appUserInfos.getMemberCode());
//            ces.setMobilePhone(appUserInfos.getMobilePhone());
//            ces.setStationId(appUserInfos.getStationId());
//            electronicMembershipCardService.insetElectronicCard(ces);
//            return electronicMembershipCardService.getElectronicCardInfoByPhone(CustomerElectronicCard.builder()
//                    .stationId(appUserInfos.getStationId())
//                    .cardOilsType(cardType)
//                    .mobilePhone(appUserInfos.getMobilePhone()).build());
//        }
//    }


    @GetMapping("/GetOrderNo")
    public long GetOrderNo() {
        Snowflake snowflake = new Snowflake(17L, 17L);
        long orderNO = snowflake.nextId();
        logger.info("====GetOrderNo返回订单号：" + orderNO);
        return orderNO;
    }

    /*
     * 小程序消费支付拉起第三方支付
     * @param payInfoRequest
     * @return
     */
    @ApiOperation(value = "消费支付拉起第三方支付", httpMethod = "POST", notes = "消费支付拉起第三方支付")
    @PostMapping(value = "/toThirdPayment")
    public String toThirdPayment(@RequestBody PayInfoRequest payInfoRequest) throws Exception {
        Gson gson = new Gson();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(payInfoRequest.getStationId()) && StringUtils.isNotBlank(payInfoRequest.getOrdNo())) {
            String stationId = payInfoRequest.getStationId();
            String ordNo = payInfoRequest.getOrdNo();
            String openId = "";
            //获取该订单信息
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrder != null) {
                if (payOrder.getStatus() != null && payOrder.getStatus().equals("0")) {

                    String payType = payOrder.getPayType();       //用户类型：1、微信；2、支付宝；
                    String orderOriginType = payOrder.getOrderOriginType();     //订单来源：1、微信小程序；2、微信公众号；3、支付宝小程序；4、支付宝公众号；
                    //获取油站的支付配置项信息
                    String payType_num = "";
                    PayWay payWay = new PayWay();
                    payWay.setStationId(Integer.valueOf(stationId));
                    switch (payType) {
                        case "wx":   //微信
                            payType_num = "1";
                            openId = payInfoRequest.getOpenId();
                            break;
                        case "zfb":  //支付宝
                            payType_num = "2";
                            openId = payInfoRequest.getAliUserId();
                            break;
                        case "yl":   //银联
                            payType_num = "3";
                            break;
                    }
                    payWay.setAppType(payType_num);        //支付宝还是微信
                    payWay.setUseType("1");             //使用类型
                    //获取该油站的支付类型
                    List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
                    HashMap<String, Object> resultMap = new HashMap<>();
                    if (payWayList != null && payWayList.size() == 1) {
                        PayOrder p = new PayOrder();                            //更新订单参数
                        String amt = payOrder.getAmt().toString();              //订单实付金额
                        //计算使用优惠券后的金额 与优惠券优惠金额
                        if (StringUtils.isNotBlank(payInfoRequest.getCouponUserId())) {
                            logger.info("用户使用的优惠券ID：" + payInfoRequest.getCouponUserId());
                            //油站信息
                            Station station = enterpriseService.selectStationById(Integer.valueOf(payOrder.getStationId()));
                            //用户信息
                            AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                                    .stationId(station.getEnterpriseId()).mobilePhone(payOrder.getCustomerPhone()).build());
                            //计算使用优惠券后传参优惠券ID
                            payOrder.setDiscountCoupon(payInfoRequest.getCouponUserId());
                            //计算优惠券
                            CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrder, station);
                            logger.info("用户使用的优惠券信息：" + couponUser);
                            if (null != couponUser) {
                                //使用优惠券时要更新的订单信息
                                amt = couponUser.getNewAmtByCoupon().toString();
                                p.setDiscountCoupon(payInfoRequest.getCouponUserId());
                                p.setDiscountCouponAmt(couponUser.getCouponAmtByCNY().doubleValue());
                                p.setAmt(Double.valueOf(amt));
                                logger.info("用户要付款的金额：" + amt);
                            }
                        }
                        String payTypeSta = payWayList.get(0).getPayType();     //第三方支付类型
                        String mno = payWayList.get(0).getMno();                //商户号
                        String subject = payOrder.getOilName() + " - " + payOrder.getStationName();
                        String appId = "";
                        String notifyUrl = "";
                        appId = payWayList.get(0).getEnterprise().getAppId();
                        switch (payTypeSta) {
                            case "1":   //随行付
                                notifyUrl = "https://" + domainName + contextPath + "/sxfPayCallback";
                                List<DivideAccountsSettingDto> divideAccList = payOrderMapper.selectDivideSettingDetail(mno, stationId);
//        处理分账
                                String ledgerAccountFlag = "0";
                                if (divideAccList.size() > 0 && divideAccList.get(0).getBeginMmo() != null) {
                                    ledgerAccountFlag = "1";
                                }


                                resultMap = SXFPayUtil.tradeJsApiScan(
                                        SXFPayParam.builder()
                                                .amt(amt)
                                                .appId(appId)
                                                .mno(mno)
                                                .ordNo(ordNo)
                                                .notifyUrl(notifyUrl)
                                                .subject(subject)
                                                .userId(openId)
                                                .ledgerAccountFlag(ledgerAccountFlag)
                                                .customerIp(payInfoRequest.getCustomerIp())
                                                .ylTrmNo(payInfoRequest.getYlTrmNo())
                                                .userType(payType_num)
                                                .weChatType("1")
                                                .build());
                                break;
                            case "2":   //圈圈（元闪付，扫呗）
                                notifyUrl = "https://" + domainName + contextPath + "/sbPayCallback";
                                resultMap = SBPayUtil.saoBeiTradePay(
                                        SBPayParam.builder()
                                                .amt(amt)
                                                .appId(appId)
                                                .userType(payType_num)
                                                .appPayType("1")
                                                .key(payWayList.get(0).getSecretKey())
                                                .openId(openId)
                                                .terminalId(payWayList.get(0).getTerminalNo())
                                                .ordNo(ordNo)
                                                .orderBody(subject)
                                                .notifyUrl(notifyUrl)
                                                .merchantNo(mno)
                                                .build());
                                break;
                            case "3":   //通联支付
                                long amtLong = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                                //通联智U+，需要实时到账，分账时预支付接口
                                if ("1".equals(payWayList.get(0).getTlFusFlag())) {
                                    notifyUrl = "https://" + domainName + contextPath + "/tLFusClassPayCallback";     //回调地址
                                    String tlFusClassPayType = "wx".equals(payType) ? "WECHATPAY_MINIPROGRAM" : "ALIPAY_SERVICE";
                                    logger.info("payway支付参数信息：" + payWayList.get(0).getPayWayId());
                                    //获取通联支付的班次标识
                                    String shiftsMask = "";
                                    String shiftsTime = "";
                                    Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
                                    if (null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")) {
                                        shiftsMask = smat.get("shiftsMask");
                                        p.setTlShiftsMask(shiftsMask);
                                        shiftsTime = smat.get("shiftsTime");
                                        p.setTlShiftsTime(shiftsTime);
                                    } else {
                                        logger.info("未设置班次");
                                    }
                                    logger.info("班次标识：" + shiftsMask + "; 班次时间：" + shiftsTime);
                                    resultMap = TLFusClassPayUtil.tLFusClassPayApply(
                                            TLFusClassPayParam.builder()
                                                    .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
                                                    .amount(amtLong)
                                                    .backUrl(notifyUrl)
                                                    .bizOrderNo(ordNo)
                                                    .sysId(payWayList.get(0).getTlSysId())
                                                    .tlAppId(payWayList.get(0).getTlAppId())
                                                    .tlAppKey(payWayList.get(0).getTlAppKey())
                                                    .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
                                                    .consumeType("C0001")                                                  //消费类型
                                                    .shiftsMask(shiftsMask)                                                //班次标识
                                                    .shiftsTime(shiftsTime)     //班次时间
                                                    .remark(subject)
                                                    .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
                                                    .payType(tlFusClassPayType)
                                                    .build());
                                } else {
                                    //通联收银宝预支付接口
                                    notifyUrl = "https://" + domainName + contextPath + "/tLPayCallback";
                                    String tlPayType = "wx".equals(payType) ? "W06" : "A02";
                                    resultMap = TLPayUtil.tLTradePay(
                                            TLPayParam.builder()
                                                    .body(subject)
                                                    .notifyUrl(notifyUrl)
                                                    .remark(subject)
                                                    .reqSn(ordNo)
                                                    .payType(tlPayType)
                                                    .acct(openId)                                               //微信用户openId
                                                    .subAppId(appId)                                            //微信appId
                                                    .sybAppId(payWayList.get(0).getAllinpayAppId())             //通联系统分配的appId 00226421 payWayList.get(0).getAllinpayAppId()
                                                    .SIGN_TYPE("RSA")                                           //通联验签加密方式  RSA； SM2； MD5；
                                                    .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())    //秘钥 RSA； SM2； MD5；
                                                    .cusId(mno)                                                 //商户号
                                                    .trxAmt(amtLong)                                            //单位分
                                                    .build());
                                }
                                break;
                        }
                        resultMap.put("thirdPayment", payTypeSta);
                        p.setOrderNo(payInfoRequest.getOrdNo());
                        p.setServiceCharge(payWayList.get(0).getServiceCharge());       //费率
                        p.setPayWayId(payWayList.get(0).getPayWayId());                 //第三方支付类型
                        if (resultMap.containsKey("merchantsNumber")) {
                            p.setMerchantsNumber(resultMap.get("merchantsNumber").toString());
                        }
                        payOrderService.getUpdatePayOrder(p);
                        resultData = ResultData.success(resultMap);
                    } else {
                        resultData = ResultData.error(CodeMsg.NOT_PAYWAY);
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.ALREADY_PAY);
                }
            } else {
                resultData = ResultData.error(CodeMsg.YEWU_FAIL, "未查询到订单");
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    @ApiOperation(value = "消费支付拉起第三方支付", httpMethod = "POST", notes = "消费支付拉起第三方支付不包含活动")
    @PostMapping(value = "/toThirdPaymentNotContainActivity")
    @Transactional
    public String toThirdPaymentNotContainActivity(@RequestBody PayInfoRequest payInfoRequest) throws Exception {
        logger.info("toThirdPaymentNotContainActivity拉起支付参数payInfoRequest{}", JSON.toJSONString(payInfoRequest));
        try {
            if (StringUtils.isBlank(payInfoRequest.getStationId()) || StringUtils.isBlank(payInfoRequest.getOrdNo())) {
                throw new EndingException("缺少必传参数");
            }
            if (StringUtils.isBlank(payInfoRequest.getOpenId()) && StringUtils.isBlank(payInfoRequest.getAliUserId())) {
                throw new EndingException("缺少用户参数");
            }

            String stationId = payInfoRequest.getStationId();
            String ordNo = payInfoRequest.getOrdNo();
            String openId = "";


            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (payOrder == null) {
                throw new EndingException("查无此单");
            }
            if (payOrder.getStatus() == null || !payOrder.getStatus().equals("0")) {
                throw new EndingException("订单状态不对");
            }

            /*String userId="";
            List<AppUserInfo>appUserInfos=appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(AppUserInfo.builder().mobilePhone(payOrder.getCustomerPhone()).stationId(payOrder.getEnterpriseId()).build());
           if(appUserInfos!=null&&appUserInfos.size()>0){
               if(appUserInfos.get(0).getYunhuaUserId()!=null){
                   userId=appUserInfos.get(0).getYunhuaUserId();
               }else {
                   userId=appUserInfos.get(0).getMobilePhone();
               }
           }*/
            //AppUserInfo appUserInfo = appUserInfoService.getById(payOrder.getConsumerId());
            String userId = null;
           /* if (StringUtils.isNotBlank(appUserInfo.getYunhuaUserId())) {
                userId = appUserInfo.getYunhuaUserId();
            }else if(!MobilePhoneUtil.isFakePhone(appUserInfo.getMobilePhone())){
                userId = appUserInfo.getMobilePhone();
            }else{
                userId = YunhuaChannel.DEFAULT_USER_ID;
            }*/
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(payOrder.getEnterpriseId());
            String payType = payOrder.getPayType();       //用户类型：1、微信；2、支付宝；
//            String orderOriginType = payOrder.getOrderOriginType();     //订单来源：1、微信小程序；2、微信公众号；3、支付宝小程序；4、支付宝公众号；
            //获取油站的支付配置项信息
            String payType_num = "";
            PayWay payWay = new PayWay();
            payWay.setStationId(Integer.valueOf(stationId));
            String payAppId = "";
            if ("wx".equals(payOrder.getPayType())) {
                if ("1".equals(payOrder.getOrderOriginType())) {
                    payAppId = enterprise.getAppId();
                }
                if ("2".equals(payOrder.getOrderOriginType())) {
                    payAppId = enterprise.getGzhAppId();
                }
            }

            switch (payType) {
                case "wx":   //微信
                    payType_num = "1";
                    openId = payInfoRequest.getOpenId();
                    break;
                case "zfb":  //支付宝
                    payType_num = "2";
                    openId = payInfoRequest.getAliUserId();
                    break;
                case "yl":   //银联
                    payType_num = "3";
                    break;
            }

            payWay.setAppType(payType_num);        //支付宝还是微信
            payWay.setUseType("1");             //使用类型
            List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay); //获取该油站的支付类型
            HashMap<String, Object> resultMap = new HashMap<>();
            if (payWayList == null && payWayList.size() != 1) {
                throw new EndingException("支付渠道数目不对");
            }
            PayOrder p = new PayOrder();                            //更新订单参数
            String amt = payOrder.getAmt().toString();              //订单实付金额

            // 优惠券逻辑
            if (!MobilePhoneUtil.isFakePhone(payOrder.getCustomerPhone()) && StringUtils.isNotBlank(payInfoRequest.getCouponUserId())) {
                //logger.info("/toThirdPay-CouponUserId：" + payInfoRequest.getCouponUserId());

                Station station = enterpriseService.selectStationById(Integer.valueOf(payOrder.getStationId()));

                //计算使用优惠券后传参优惠券ID
                /*payOrder.setDiscountCoupon(payInfoRequest.getCouponUserId());
                //计算优惠券
                CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrder, station);

                if (couponUser != null) {
                    //使用优惠券时要更新的订单信息
                    //amt = couponUser.getNewAmtByCoupon().toString();
                    p.setDiscountCoupon(payInfoRequest.getCouponUserId());
                    p.setDiscountCouponAmt(payOrder.getReceivableAmt()-payOrder.getAmt()-payOrder.getDiscountAmt());

                }*/

            }

            String payTypeSta = payWayList.get(0).getPayType();     //第三方支付类型
            String mno = payWayList.get(0).getMno();                //商户号
            String subject = "" + " - " + payOrder.getStationName();
            String appId = payWayList.get(0).getEnterprise().getAppId();
            String notifyUrl = "";
            String weChatType = "2";
            if (payInfoRequest.getPayAppType() != null && !"".equals(payInfoRequest.getPayAppType()) && "1".equals(payInfoRequest.getPayAppType())) {
                weChatType = "1";
            }

            logger.info("wetchatType---------------------------" + weChatType);
            switch (payTypeSta) {
                case "1":   //随行付
                    notifyUrl = "https://" + domainName + contextPath + "/sxfPayCallbackV2";
                    List<DivideAccountsSettingDto> divideAccList = payOrderMapper.selectDivideSettingDetail(mno, stationId);
//        处理分账
                    String ledgerAccountFlag = "0";
                    if (divideAccList.size() > 0 && divideAccList.get(0).getBeginMmo() != null) {
                        ledgerAccountFlag = "1";
                    }
                    resultMap = SXFPayUtil.sxfGoPay(
                            SXFPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .mno(mno)
                                    .ordNo(ordNo)
                                    .notifyUrl(notifyUrl)
                                    .subject(subject)
                                    .userId(openId)
                                    .customerIp(payInfoRequest.getCustomerIp())
                                    .ylTrmNo(payInfoRequest.getYlTrmNo())
                                    .userType(payType_num)
                                    .weChatType(weChatType)
                                    .ledgerAccountFlag(ledgerAccountFlag)
                                    .build());
                    break;
                case "2":   //圈圈（元闪付，扫呗）
                    notifyUrl = "https://" + domainName + contextPath + "/sbPayCallback";
                    resultMap = SBPayUtil.saoBeiTradePay(
                            SBPayParam.builder()
                                    .amt(amt)
                                    .appId(appId)
                                    .userType(payType_num)
                                    .appPayType("1")
                                    .key(payWayList.get(0).getSecretKey())
                                    .openId(openId)
                                    .terminalId(payWayList.get(0).getTerminalNo())
                                    .ordNo(ordNo)
                                    .orderBody(subject)
                                    .notifyUrl(notifyUrl)
                                    .merchantNo(mno)
                                    .build());
                    resultMap.put("payAppId", payAppId);

                    break;
                case "3":   //通联支付
                    long amtLong = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    //通联智U+，需要实时到账，分账时预支付接口
                    if ("1".equals(payWayList.get(0).getTlFusFlag())) {
                        notifyUrl = "https://" + domainName + contextPath + "/tLFusClassPayCallback";     //回调地址
                        String tlFusClassPayType = "wx".equals(payType) ? "WECHATPAY_MINIPROGRAM" : "ALIPAY_SERVICE";
                        logger.info("payway支付参数信息：" + payWayList.get(0).getPayWayId());
                        //获取通联支付的班次标识
                        String shiftsMask = "";
                        String shiftsTime = "";
                        Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
                        if (null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")) {
                            shiftsMask = smat.get("shiftsMask");
                            p.setTlShiftsMask(shiftsMask);
                            shiftsTime = smat.get("shiftsTime");
                            p.setTlShiftsTime(shiftsTime);
                        } else {
                            logger.info("未设置班次");
                        }
                        logger.info("班次标识：" + shiftsMask + "; 班次时间：" + shiftsTime);
                        resultMap = TLFusClassPayUtil.tLFusClassPayApply(
                                TLFusClassPayParam.builder()
                                        .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
                                        .amount(amtLong)
                                        .backUrl(notifyUrl)
                                        .bizOrderNo(ordNo)
                                        .sysId(payWayList.get(0).getTlSysId())
                                        .tlAppId(payWayList.get(0).getTlAppId())
                                        .tlAppKey(payWayList.get(0).getTlAppKey())
                                        .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
                                        .consumeType("C0001")                                                  //消费类型
                                        .shiftsMask(shiftsMask)                                                //班次标识
                                        .shiftsTime(shiftsTime)     //班次时间
                                        .remark(subject)
                                        .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
                                        .payType(tlFusClassPayType)
                                        .build());
                        resultMap.put("payAppId", payAppId);
                    } else {
                        //通联收银宝预支付接口
                        notifyUrl = "https://" + domainName + contextPath + "/tLPayCallback";
                        String tlPayType = "wx".equals(payType) ? "W06" : "A02";
                        resultMap = TLPayUtil.tLTradePay(
                                TLPayParam.builder()
                                        .body(subject)
                                        .notifyUrl(notifyUrl)
                                        .remark(subject)
                                        .reqSn(ordNo)
                                        .payType(tlPayType)
                                        .acct(openId)                                               //微信用户openId
                                        .subAppId(appId)                                            //微信appId
                                        .sybAppId(payWayList.get(0).getAllinpayAppId())             //通联系统分配的appId 00226421 payWayList.get(0).getAllinpayAppId()
                                        .SIGN_TYPE("RSA")                                       //通联验签加密方式  RSA； SM2； MD5；
                                        .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())    //秘钥 RSA； SM2； MD5；
                                        .cusId(mno)                                                 //商户号
                                        .trxAmt(amtLong)                                            //单位分
                                        .build());
                        resultMap.put("payAppId", payAppId);
                    }
                    break;
                case "4":   //金控支付
                    notifyUrl = "https://" + domainName + contextPath + "/JKNotice";
                    long amtLong1 = new BigDecimal(amt).multiply(new BigDecimal("100")).longValue();
                    resultMap = JKPayUtil.JKPay(JKPayParam.builder()
                            .merchantNo(payWayList.get(0).getMno())
                            .orderNo(ordNo)
                            .notifyUrl(notifyUrl)
                            .amt(amtLong1 + "")
                            .appId(appId)
                            .openId(openId)
                            .private_pfxPath(private_pfxPath)
                            .public_certPath(public_certPath)
                            .buyerId(openId)
                            .payChannelCode(payType_num)
                            .build());
                    resultMap.put("payAppId", payAppId);
                    break;
                case "5":   //云华支付
//                    notifyUrl = "https://" + domainName + contextPath + "/yunHuaNotice";
//                    String   payFor="wx_jsapi";
//                    if("wx".equals(payOrder.getPayType())){
//
//                        if("1".equals(payOrder.getOrderOriginType())){
//                            payFor="wx_minipay";
//                        }
//                        if("2".equals(payOrder.getOrderOriginType())){
//                            payFor="wx_jsapi";
//                        }
//
//                    }else if("zfb".equals(payOrder.getPayType())) {
//                        payFor="";
//                    }
//                    String nowdate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//                    resultMap = yunHuaPayUtils.yunHuaPay(YunHuaParam.builder()
//                            .clientOrgCode(payWayList.get(0).getMno())
//                            .lockFlag("lock")
//                            .noticeUrl(notifyUrl)
//                            .partnerCode(payWayList.get(0).getTerminalNo())
//                            .payChannelId(payFor)
//                            .posOrderNo(ordNo)
//                            .reqTime(nowdate)
//                            .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
//                            .vsOrderNo(ordNo)
//                            .openId(openId)
//                            .carRefueling(nowdate)
//                            .build());
//                    resultMap.put("payAppId",payAppId);

                    notifyUrl = "https://" + domainName + contextPath + "/yunHuaNotice";
                    logger.info("weChatType{}", weChatType);
                    String txnDesc = "收款码";
                    switch (payType) {
                        case "zfb":
                            logger.info("支付宝拉起支付");

                            if (payOrder.getOilName() != null) {
                                txnDesc = payOrder.getOilName();
                            }
                            resultMap = yunHuaPayUtils.yunHuaPayAli(YunHuaParam.builder()
                                    .partnerCode(payWayList.get(0).getMno())
                                    .posOrderNo(ordNo)
                                    .openId(openId)
                                    .noticeUrl(notifyUrl)
                                    .txnDesc(txnDesc)
                                    .miniUrl("www.123.com")
                                    .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                    .userId(userId)
                                    .build(), payWayList.get(0).getSecretKey(), yunhuaPayUrl);
                            break;

                        case "wx":
                            if (weChatType.equals("1")) {
                                //小程序
                                logger.info("小程序拉起支付");
                                resultMap = yunHuaPayUtils.yunHuaPayWxMini(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .miniUrl("www.123.com")
                                        .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                        .userId(userId)
                                        .build(), payWayList.get(0).getSecretKey(), yunHuaPrePayUrl);
                            } else {
                                logger.info("公众号拉起支付");

                                if (payOrder.getOilName() != null) {
                                    txnDesc = payOrder.getOilName();
                                }
                                resultMap = yunHuaPayUtils.yunHuaPayV2(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .txnDesc(txnDesc)
                                        .txnAmt((BigDecimal.valueOf(Double.valueOf(amt))))
                                        .userId(userId)
                                        .build(), payWayList.get(0).getSecretKey(), yunHuaPrePayUrl);
                            }
                    }
                    resultMap.put("payAppId", payAppId);
                    break;
            }

            resultMap.put("thirdPayment", payTypeSta);
            p.setOrderNo(payInfoRequest.getOrdNo());
//            p.setServiceCharge(payWayList.get(0).getServiceCharge());       //费率
            p.setPayWayId(payWayList.get(0).getPayWayId());                 //第三方支付类型
            if (resultMap.containsKey("merchantsNumber")) {
                p.setMerchantsNumber(resultMap.get("merchantsNumber").toString());
            }
            payOrderService.getUpdatePayOrder(p);
            logger.info("返回值{}", resultMap);
            return ResultData.successJson(resultMap);


        } catch (EndingException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJsonWithCode(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("/toThirdPaymentNotContainActivity-", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }
    }

    /*
     * 小程序消费 通联智U+，需要实时到账，分账时 获取班次时间与班次标识
     * @param payWayId
     * @return
     * @throws ParseException
     */
    public Map<String, String> getShiftsMaskAndTime(Integer payWayId) throws ParseException {
        Map<String, String> resultMap = new HashMap<>();
        if (null != payWayId) {
            String shiftsMask = "";
            String shiftsTime = "";
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            List<ShiftClass> shiftClassList = enterpriseService.selectShiftClassList(ShiftClass.builder().payWayId(payWayId).build());
            if (null != shiftClassList && shiftClassList.size() > 0) {
                for (ShiftClass sc : shiftClassList) {
                    //如果开始时间小于结束时间，做处理
                    if (sc.getShiftStartTime().compareTo(sc.getShiftEndTime()) <= 0) {
                        if (sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >= 0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) < 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                    } else {
                        //否则开始时间大于结束时间
                        if (sdf.format(new Date()).compareTo(sc.getShiftStartTime().toString()) >= 0 && sdf.format(new Date()).compareTo("23:59:59") <= 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                        if (sdf.format(new Date()).compareTo("00:00:00") >= 0 && sdf.format(new Date()).compareTo(sc.getShiftEndTime().toString()) < 0) {
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = LocalDate.now().plusDays(-1).toString().replace("-", "");
                            break;
                        }
                    }
                }
            }
            logger.info("shiftsMask：" + shiftsMask + "; shiftsTime:" + shiftsTime);
            resultMap.put("shiftsMask", shiftsMask);
            resultMap.put("shiftsTime", shiftsTime);
        }
        return resultMap;
    }

    /*
     * 小程序消费 通联智U+，需要实时到账，分账时预支付接口 回调
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/tLFusClassPayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
    @Transactional
    public void tLFusClassPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        JSONObject resultJson = new JSONObject();
        logger.info("========================================通联智U+，需要实时到账，分账时预支付接口 回调开始 ========================================");
        System.out.println("通联支付接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        TreeMap<String, String> params = getParams(request);  //动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        logger.info("通联智U+，需要实时到账，分账返回TreeMap参数：" + params.toString());
        //通联返回TreeMap参数：
         /*{appId=M00000048,
         bizContent={"finishTime":"20220121100336",
                     "amount":"1",
                     "orderNo":"P20220121000000012525253",  //通联订单号
                     "sysId":"1480833167961694210",
                     "remark":"98# - 趣加西站",
                     "shiftsTime":"20220121",
                     "shiftsMask":"1",
                     "tradeDirection":"00",
                     "payType":"WECHATPAY_MINIPROGRAM",
                     "createTime":"20220121100328",
                     "payStatus":"0000",                    //
                     "bizOrderNo":"1642730605601844285"},   //商户订单号
         charset=utf-8,
         service=oil.pay.notify,
         sign=82995d03e8bb7e5f863f946ab937dc92,
         signType=MD5,
         timestamp=20220121100336,
         version=1.0}
         */
        //SignUtils.verify(params);
        try {
            Map<String, String> bizContent = JSONObject.parseObject(params.get("bizContent"), Map.class);
            //logger.info("bizContent内容信息：" + bizContent);
            String ordNo = bizContent.get("bizOrderNo");    //商户订单号
            String orderNo = bizContent.get("orderNo");     //通联订单号
            double amt = new BigDecimal(bizContent.get("amount")).divide(new BigDecimal("100")).doubleValue();
            String finishTime = bizContent.get("finishTime");
            String payType = "WECHATPAY_MINIPROGRAM".equals(bizContent.get("payType")) ? "wx" : "zfb";
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            List<PayWay> payWayList = enterpriseService.selectStaPayWay(PayWay.builder().payWayId(payOrderInfo.getPayWayId()).build());
            //boolean isSign = SybUtil.validSign(params, payWayList.get(0).getTlAppKey(), params.get("signType"));
            //验签
            params.put("key", payWayList.get(0).getTlAppKey());
            boolean isSign = SignUtils.verify(params);
            logger.info("通联智U+，实时到账，分账回调验签结果：" + isSign);
            if (isSign) {
                resultJson.put("code", "SUCCESS");
                resultJson.put("msg", "SUCCESS");
                resultJson.put("bizCode", "0000");
                resultJson.put("bizMsg", "SUCCESS");
                TreeMap<String, String> map = new TreeMap<String, String>();
                map.put("code", "SUCCESS");
                map.put("msg", "SUCCESS");
                map.put("bizCode", "0000");
                map.put("bizMsg", "SUCCESS");
                map.put("key", payWayList.get(0).getTlAppKey());
                String sign = SignUtils.sign(map);
                resultJson.put("sign", sign);
                if (null != payOrderInfo && "0".equals(payOrderInfo.getStatus())) {

                    //logger.info("通联智U+，实时到账，分账回调验签成功");
                    Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
                    int count = payOrderService.getUpdatePayOrder(PayOrder.builder()
                            .orderNo(ordNo)
                            .status("1")
                            .dzkAmt(Double.valueOf("0"))
                            .receivedAmt(amt)
                            .wxAmt(amt)
                            .payType(payType)
                            .payDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(finishTime).getTime()))
                            .transactionId(null)
                            .build());
                    //  飞鹅打印机打印订单
                    gzhNewsTemplateService.feiePush(payOrderInfo);
                    gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
                    if (1 == count) {
                        logger.info("通联智U+，需要实时到账，分账 更新订单成功");
                        if (station != null && station.getEnterpriseId() != null) {
                            //计算积分 成长值
                            Integer enterpriseId = station.getEnterpriseId();   //油企ID
                            CalculateIntegral calculateIntegral = new CalculateIntegral();
                            calculateIntegral.setEnterpriseId(enterpriseId);
                            calculateIntegral.setOilId(payOrderInfo.getOilId());
                            calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
                            calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
                            calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
                            CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
                            payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(), ordNo);
                            //更新积分，成长值
                            if (StringUtils.isNotBlank(payOrderInfo.getCustomerPhone())) {
                                logger.info("客户手机号：" + payOrderInfo.getCustomerPhone());
                                AppUserInfo appUserInfo = new AppUserInfo();
                                appUserInfo.setStationId(enterpriseId);
                                //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                                appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                                AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                                if (null != userInfo) {
                                    logger.info("用户信息原有：成长值" + userInfo.getGrowUpValue() + ";积分：" + userInfo.getIntegral());
                                    Integer integral = userInfo.getIntegral();
                                    Integer growUpValue = userInfo.getGrowUpValue();
                                    logger.info("用户信息本次加油后获得的：成长值" + calIntegral.getGrowValue() + ";积分：" + calIntegral.getIntegral());
                                    appUserInfo.setIntegral(calIntegral.getIntegral() + integral);
                                    appUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
                                    appUserInfoService.updateAppUserIntegral(appUserInfo);

                                    //生成积分记录
                                    calculateIntegral.setStationId(payOrderInfo.getStationId());
                                    calculateIntegral.setNickName(userInfo.getBlogNickName());
                                    calculateIntegral.setOrderNo(payOrderInfo.getOrderNo());
                                    calculateIntegral.setUnionId(userInfo.getUnionId());
                                    calculateIntegral.setMobilePhone(userInfo.getMobilePhone());
                                    this.createIntegralRecord(calculateIntegral, payType, appUserInfo.getIntegral());

                                    //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                                    if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                        //修改优惠券状态
                                        if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {

                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("couponUserId", payOrderInfo.getDiscountCoupon());
                                            List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                            if (null != couponUserList && couponUserList.size() == 1) {
                                                couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                                CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                                if (null != ct) {
                                                    couponService.updateCouponTemplate(CouponTemplate.builder()
                                                            .useCouponNum(ct.getUseCouponNum() + 1)
                                                            .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                            .build());
                                                }
                                            }

//                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
//                                            couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
//                                            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).build());
//                                            if(null != ct){
//                                                couponService.updateCouponTemplate(CouponTemplate.builder()
//                                                        .useCouponNum(ct.getUseCouponNum()+1)
//                                                        .couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon()))
//                                                        .build());
//                                            }
                                        }
                                        int i = couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()), ordNo);
                                        //优惠券主动领取后推送消息
                                        if (i > 0)
                                            couponService.pushWxGzhInitiativeCouponInfo(station, payOrderInfo, i, appUserInfo);
                                    }
                                    logger.info("=========================================通联智U+，需要实时到账，分账回调后业务完成！===============================================================");
                                    //积分推送
//                                    calculateIntegral.setBlogOpenid(userInfo.getBlogOpenid());
//                                    this.pushIntegralToUser(appUserInfo, station, calculateIntegral);
                                    userInfo.setIntegral(userInfo.getIntegral() + calIntegral.getIntegral());
                                    userInfo.setGrowUpValue(userInfo.getGrowUpValue() + calIntegral.getGrowValue());
                                    gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
                                }

                            } else {
                                logger.info("更新用户积分时，用户手机号不存在");
                            }
                        } else {
                            logger.info("通联智U+，需要实时到账，分账回调该油站不存在或者油企ID为空");
                        }

                    } else {
                        logger.info("通联智U+，需要实时到账，分账 回调更新订单失败");
                    }
                } else {
                    logger.info("该订单已支付完成");
                }
            } else {
                logger.info("通联智U+，需要实时到账，分账回调 验签失败");
            }
        } catch (Exception e) {//处理异常
            e.printStackTrace();
        } finally {//收到通知,返回success
            response.getOutputStream().write(resultJson.toString().getBytes());
            response.flushBuffer();
        }
    }

    /*
     * 小程序消费  通联收银宝异步回调通知
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/tLPayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
    @Transactional
    public void tLPayCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通联返回字段：{randomstr=919944628264, cusid=55358805541929E, appid=00227498, sign=lK3fve/RzBEampj7ArJ7WBu08802YHfkexKVXmAjw6AA1GT7b2SVKwLF64FvTqZpTiFhydBkodHQmZQRRKhIMX7wzhfphaXYr37fhXVSwtfoVJV2QJdRrcekLNDuQfzOowEeq1S0qmkNGbd5JvDbjIn29gpWjevxJb/v2YPp0TQ=, payinfo={"appId":"wxe1135cd390b38a54","timeStamp":"1640163543","nonceStr":"c3b36b7698a54ede9cdfcf9d1b75650d","package":"prepay_id=wx22165903665284e461c00143c396290000","signType":"RSA","paySign":"Vuy+4EpvTptrzYSeVMh1kqxVwge+fqGhEjFMvnGnQFxya0tCKkv7zWNt8PbUo0m2D0/WmkCWNVFxRUsbL8m+8dmjux+U8RJtBJsh/UgbKm0PxCel4bN5SBhI8gcD9H1ZRnaRMvl8SMtABOiKIV74w+98UH1XaL6Xq+tVYN5sgkUZlC9qa6ERgdqlcsJBk+syDeRuZsB9sFwALRlHJTHLVOW78Lcd1RHfe50XJtMZpL+YSZ6DGoXhxrAVjhSd3Ojy8SZlc8E9Gw27XLLkohplXr5pA9s+/Qrqj0oXMzvj0Br9QeMrAqyK4lKzJ4837McaTYftHm1/dfMtorsjHuRMJQ=="}, trxid=211222119610044247, trxstatus=0000, reqsn=1640163541377295272, retcode=SUCCESS}
        System.out.println("通联收银宝支付接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
        response.setCharacterEncoding("UTF-8");
        TreeMap<String, String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        logger.info("通联收银宝返回参数：" + params.toString());
        try {
            String ordNo = params.get("cusorderid");    //订单号
            String trxcode = params.get("trxcode");     //交易类型
            String trxamt = params.get("trxamt");       //交易金额
            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
            Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
            String payType = "VSP501".equals(trxcode) ? "wx" : "zfb";
//            String appType = "wx".equals(payType) ? "1" : "2";
//            List<PayWay> payWayList = enterpriseService.selectStaPayWay(PayWay.builder()
//                    .stationId(payOrderInfo.getStationId())
//                    .appType(appType)
//                    .useType("1").build());
//            String appkey = payWayList.get(0).getAllinpayRSAKey();
            boolean isSign = SybUtil.validSign(params, SybConstants.SYB_RSATLPUBKEY, SybConstants.SIGN_TYPE);         // 接受到推送通知,首先验签
            System.out.println("通联收银宝验签结果:" + isSign);
            //验签完毕进行业务处理
            if (isSign) {
                if (null != payOrderInfo && "0".equals(payOrderInfo.getStatus())) {
                    //飞鹅打印机  打印订单
                    gzhNewsTemplateService.feiePush(payOrderInfo);
                    gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);
                    //验签：
                    Integer enterpriseId = station.getEnterpriseId();
                    PayOrder p = new PayOrder();
                    p.setOrderNo(ordNo);
                    p.setStatus("1");
                    p.setPayType(payType);
                    p.setDzkAmt(Double.valueOf("0"));
                    double amt = new BigDecimal(trxamt).divide(new BigDecimal("100")).doubleValue();
                    p.setWxAmt(amt);
                    Date parse = new SimpleDateFormat("yyyyMMddHHmmss").parse(params.get("paytime"));
                    p.setPayDate(new Timestamp(parse.getTime()));               //支付时间
                    p.setReceivedAmt(amt);                                      //settleAmt商家入账金额
                    if (params.containsKey("chnltrxid")) {
                        p.setTransactionId(params.get("chnltrxid"));                //如支付宝，微信平台订单号
                    }
                    //修改订单状态
                    //(String orderNo,String mobilePhone,BigDecimal amt, Long enterpriseId, Long stationId,String payType,String cardOilsType,String oilId,String bussinessName,String purpose);
                    //}
              /*      customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(ordNo,
                            payOrderInfo.getCustomerPhone(),new BigDecimal(amt),enterpriseId.longValue(),
                            payOrderInfo.getStationId().longValue(),payType,null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/
                    int count = payOrderService.getUpdatePayOrder(p);
                    if (1 == count) {
                        logger.info("通联收银宝更新订单成功！");
                        //1、更新积分；
                        if (station != null && station.getEnterpriseId() != null) {
                            //计算积分 成长值
                            CalculateIntegral calculateIntegral = new CalculateIntegral();
                            calculateIntegral.setEnterpriseId(enterpriseId);
                            calculateIntegral.setOilId(payOrderInfo.getOilId());
                            calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
                            calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
                            calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
                            CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
                            payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(), ordNo);
                            //更新积分，成长值
                            if (StringUtils.isNotBlank(payOrderInfo.getCustomerPhone())) {
                                logger.info("客户手机号：" + payOrderInfo.getCustomerPhone());
                                AppUserInfo appUserInfo = new AppUserInfo();
                                appUserInfo.setStationId(enterpriseId);
                                //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                                appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                                AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                                if (null != userInfo) {
                                    logger.info("用户信息原有：成长值" + userInfo.getGrowUpValue() + ";积分：" + userInfo.getIntegral());
                                    Integer integral = userInfo.getIntegral();
                                    Integer growUpValue = userInfo.getGrowUpValue();
                                    logger.info("用户信息本次加油后获得的：成长值" + calIntegral.getGrowValue() + ";积分：" + calIntegral.getIntegral());
                                    appUserInfo.setIntegral(calIntegral.getIntegral() + integral);
                                    appUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
                                    appUserInfoService.updateAppUserIntegral(appUserInfo);

                                    //生成积分记录
                                    calculateIntegral.setStationId(payOrderInfo.getStationId());
                                    calculateIntegral.setNickName(userInfo.getBlogNickName());
                                    calculateIntegral.setOrderNo(payOrderInfo.getOrderNo());
                                    calculateIntegral.setUnionId(userInfo.getUnionId());
                                    calculateIntegral.setMobilePhone(userInfo.getMobilePhone());
                                    this.createIntegralRecord(calculateIntegral, p.getPayType(), appUserInfo.getIntegral());

                                    //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                                    if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                        //修改优惠券状态
                                        if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {

                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("couponUserId", payOrderInfo.getDiscountCoupon());
                                            List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                            if (null != couponUserList && couponUserList.size() == 1) {
                                                couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                                CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                                if (null != ct) {
                                                    couponService.updateCouponTemplate(CouponTemplate.builder()
                                                            .useCouponNum(ct.getUseCouponNum() + 1)
                                                            .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                            .build());
                                                }
                                            }

//                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
//                                            couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
//                                            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).build());
//                                            if(null != ct){
//                                                couponService.updateCouponTemplate(CouponTemplate.builder()
//                                                        .useCouponNum(ct.getUseCouponNum()+1)
//                                                        .couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon()))
//                                                        .build());
//                                            }
                                        }
                                        int i = couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()), ordNo);
                                        //优惠券主动领取后推送消息
                                        if (i > 0)
                                            couponService.pushWxGzhInitiativeCouponInfo(station, payOrderInfo, i, appUserInfo);
                                    }
                                    logger.info("=========================================通联收银宝回调后业务完成！===============================================================");
                                    //积分推送
//                                    calculateIntegral.setBlogOpenid(userInfo.getBlogOpenid());
//                                    this.pushIntegralToUser(appUserInfo, station, calculateIntegral);
                                    userInfo.setIntegral(userInfo.getIntegral() + calIntegral.getIntegral());
                                    userInfo.setGrowUpValue(userInfo.getGrowUpValue() + calIntegral.getGrowValue());
                                    gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
                                }

                            } else {
                                logger.info("更新用户积分时，用户手机号不存在");
                            }
                        } else {
                            logger.info("该油站不存在或者油企ID为空");
                        }
                    } else {
                        logger.info("更新订单失败！");
                    }
                } else {
                    logger.info("订单已更新！");
                }
            } else {
                logger.info("验签失败");
            }
        } catch (Exception e) {//处理异常
            e.printStackTrace();
        } finally {//收到通知,返回success
            response.getOutputStream().write("success".getBytes());
            response.flushBuffer();
        }
    }

    /**
     * 通联 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     *
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request) {
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for (Object key : reqMap.keySet()) {
            String value = ((String[]) reqMap.get(key))[0];
            //System.out.println(key+";"+value);
            map.put(key.toString(), value);
        }
        return map;
    }


    /*
     * 小程序消费  随行付异步回调通知
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/sxfPayCallback", consumes = "application/json", method = RequestMethod.POST)
    @Transactional
    public JSONObject sxfPayCallback(@RequestBody JSONObject request) throws ParseException {
        logger.info("/sxfPayCallback" + "-" + request.get("ordNo").toString() + "--request:" + request);
        JSONObject resultJson = new JSONObject();
        //*********************************** 必返回参数 *******************************************//


        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        //String extend = extend=request.get("extend").toString();//备用

        //将业务参数存放在 JSON 对象中
        JSONObject reqData = new JSONObject();

        //随行付落单号
        if (request.containsKey("sxfUuid") && request.get("sxfUuid") != null) {
            String sxfUuid = request.get("sxfUuid").toString();
            reqData.put("sxfUuid", sxfUuid);
        }

        //随行付交易方式
        if (request.containsKey("payWay") && request.get("payWay") != null) {
            String payWay = request.get("payWay").toString();                 //随行付交易方式
            reqData.put("payWay", payWay);
        }

        String payWay = request.get("payWay").toString();                 //随行付交易方式
        reqData.put("payWay", payWay);


        String payTime = request.get("payTime").toString();               //随行付交易时间
        reqData.put("payTime", payTime);

        String uuid = request.get("uuid").toString();                     //随行付交易流水号
        reqData.put("uuid", uuid);

        String mno = request.get("mno").toString();                       //发起交易的商户编号
        reqData.put("mno", mno);

        String ordNo = request.get("ordNo").toString();                   //商户生成的订单号
        reqData.put("ordNo", ordNo);

        String amt = request.get("amt").toString();                       //金额
        reqData.put("amt", amt);

        String payType = request.get("payType").toString();               //对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
        reqData.put("payType", payType);

        //用户登录
        if (request.containsKey("buyerId") && request.get("buyerId") != null) {
            String buyerId = request.get("buyerId").toString();               //用户登录
            reqData.put("buyerId", buyerId);
        }

        String transactionId = "";
        if (request.containsKey("transactionId") && request.get("transactionId") != null) {
            transactionId = request.get("transactionId").toString();               //用户登录
            reqData.put("transactionId", transactionId);
        }

        if (request.containsKey("drType") && request.get("drType") != null) {
            String drType = request.get("drType").toString();               //借贷记标识 1-借,2-贷，3-其他
            reqData.put("drType", drType);
        }

        if (request.containsKey("pointAmount") && request.get("pointAmount") != null) {
            String pointAmount = request.get("pointAmount").toString();               //代金券金额
            reqData.put("pointAmount", pointAmount);
        }

        if (request.containsKey("payBank") && request.get("payBank") != null) {
            String payBank = request.get("payBank").toString();               //付款银行银行编码，例如 ICBC
            reqData.put("payBank", payBank);
        }

        if (request.containsKey("totalOffstAmt") && request.get("totalOffstAmt") != null) {
            String totalOffstAmt = request.get("totalOffstAmt").toString();               //消 费 者 付 款金额
            reqData.put("totalOffstAmt", totalOffstAmt);
        }

        String settleAmt = request.get("settleAmt").toString();           //商家入账金额
        reqData.put("settleAmt", settleAmt);

        if (request.containsKey("timeStamp") && request.get("timeStamp") != null) {
            String timeStamp = request.get("timeStamp").toString();           //响应时间
            reqData.put("timeStamp", timeStamp);
        }


        String sign = request.get("sign").toString();                     //签名
        //reqData.put("sign", sign);

        if (request.containsKey("bizCode") && request.get("bizCode") != null) {
            String bizCode = request.get("bizCode").toString();               //业务返回码
            reqData.put("bizCode", bizCode);
        }
        if (request.containsKey("bizMsg") && request.get("bizMsg") != null) {
            String bizMsg = request.get("bizMsg").toString();               //业 务 返 回 信息
            reqData.put("bizMsg", bizMsg);
        }
        if (request.containsKey("openid") && request.get("openid") != null) {
            String openid = request.get("openid").toString();               //微 信 或 支 付宝身份id()opendid userid
            reqData.put("openid", openid);
        }
        if (request.containsKey("channelId") && request.get("channelId") != null) {
            String channelId = request.get("channelId").toString();               //渠道商户号
            reqData.put("channelId", channelId);
        }
        if (request.containsKey("subMechId") && request.get("subMechId") != null) {
            String subMechId = request.get("subMechId").toString();               //子商户号
            reqData.put("subMechId", subMechId);
        }
        if (request.containsKey("finishTime") && request.get("finishTime") != null) {
            String finishTime = request.get("finishTime").toString();               //交易完成时间
            reqData.put("finishTime", finishTime);
        }
        if (request.containsKey("clearDt") && request.get("clearDt") != null) {
            String clearDt = request.get("clearDt").toString();
            reqData.put("clearDt", clearDt);
        }
        if (request.containsKey("settlementBatchNo") && request.get("settlementBatchNo") != null) {
            String settlementBatchNo = request.get("settlementBatchNo").toString();
            reqData.put("settlementBatchNo", settlementBatchNo);
        }

        //支付场景
        if (request.containsKey("scene") && request.get("scene") != null) {
            String scene = request.get("scene").toString();
            reqData.put("scene", scene);
        }

        //recFeeRate
        if (request.containsKey("recFeeRate") && request.get("recFeeRate") != null) {
            String recFeeRate = request.get("recFeeRate").toString();
            reqData.put("recFeeRate", recFeeRate);
        }

        //消 费 者 到 账金额
        if (request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") != null) {
            String refBuyerAmt = request.get("refBuyerAmt").toString();
            reqData.put("refBuyerAmt", refBuyerAmt);
        }

        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
        if (request.containsKey("buyerAccount") && request.get("buyerAccount") != null) {
            String buyerAccount = request.get("buyerAccount").toString();
            reqData.put("buyerAccount", buyerAccount);
        }

        //备用
        if (request.containsKey("extend") && request.get("extend") != null) {
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
        }

        //优惠券参数
        if (request.containsKey("promotionDetail") && request.get("promotionDetail") != null) {
            String promotionDetail = request.get("promotionDetail").toString();
            reqData.put("promotionDetail", promotionDetail);
        }
        //商家出账金额
        if (request.containsKey("realRefundAmount") && request.get("realRefundAmount") != null) {
            String realRefundAmount = request.get("realRefundAmount").toString();
            reqData.put("realRefundAmount", realRefundAmount);
        }
        //szltFlag
        if (request.containsKey("szltFlag") && request.get("szltFlag") != null) {
            String szltFlag = request.get("szltFlag").toString();
            reqData.put("szltFlag", szltFlag);
        }
        //recFeeAmt
        if (request.containsKey("recFeeAmt") && request.get("recFeeAmt") != null) {
            String recFeeAmt = request.get("recFeeAmt").toString();
            reqData.put("recFeeAmt", recFeeAmt);
        }
        //szltRecfeeAmt
        if (request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") != null) {
            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
        }

        //extend
        if (request.containsKey("extend") && request.get("extend") != null) {
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
        }

        //reqData.put("extend",extend);

//        reqData.put("sxfUuid",sxfUuid);
//        reqData.put("payWay",payWay);
//        reqData.put("payTime",payTime);
//        reqData.put("uuid",uuid);
//        reqData.put("mno",mno);
//        reqData.put("ordNo",ordNo);
//        reqData.put("amt",amt);
//        reqData.put("buyerId",buyerId);
//        reqData.put("transactionId",transactionId);
//        reqData.put("drType",drType);
//        reqData.put("payType",payType);
//        reqData.put("payBank",payBank);
//        reqData.put("pointAmount",pointAmount);
//        reqData.put("totalOffstAmt",totalOffstAmt);
//        reqData.put("settleAmt",settleAmt);
//        reqData.put("timeStamp",timeStamp);
//        reqData.put("bizCode",bizCode);
//        reqData.put("bizMsg",bizMsg);
//        reqData.put("openid",openid);
//        reqData.put("channelId",channelId);
//        reqData.put("subMechId",subMechId);
//        reqData.put("finishTime",finishTime);
//        reqData.put("clearDt",clearDt);
//        reqData.put("settlementBatchNo",settlementBatchNo);

        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);

        Gson gson = new Gson();
        //根据回调信息，先进行验签，验签后修改状态
        logger.info("/sxfPayCallback" + "-" + request.get("ordNo").toString() + "--待验签数据:" + gson.toJson(reqData));
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData), LinkedHashMap.class, Feature.OrderedField);
        //验签
        String resultStr = RSASignature.getOrderContent(result);
        System.out.println(resultStr);
//        if (RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)) {
        resultJson.put("code", "success");
        resultJson.put("msg", "成功");
        logger.info("/sxfPayCallback" + "-" + request.get("ordNo").toString() + "--验签成功");
        PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(ordNo);
        if (payOrderInfo != null) {
            if (payOrderInfo != null && "0".equals(payOrderInfo.getStatus())) {
                PayOrder payOrder = new PayOrder();
                payOrder.setOrderNo(ordNo);
                payOrder.setStatus("1");
                if (payType.equals("WECHAT")) {   //WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
                    payOrder.setPayType("wx");
                    payOrder.setWxAmt(Double.valueOf(amt));
                } else if (payType.equals("ALIPAY")) {
                    payOrder.setPayType("zfb");
                    payOrder.setZfbAmt(Double.valueOf(amt));
                } else if (payType.equals("UNIONPAY")) {
                    payOrder.setPayType("yl");
                }

                payOrder.setDzkAmt(Double.valueOf("0"));
                //new SimpleDateFormat("YYYYMMDDHHmmss").parse("20211221153859")
                payOrder.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime).getTime()));    //支付时间
                payOrder.setReceivedAmt(Double.valueOf(settleAmt));          //settleAmt商家入账金额
                payOrder.setTransactionId(transactionId);
                //修改订单状态


                int count = payOrderService.getUpdatePayOrder(payOrder);
                if (count == 1) {
                    logger.info("更新订单状态成功，随行付支付完成！");

                    Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
                    if (station != null && station.getEnterpriseId() != null) {

                        Integer enterpriseId = station.getEnterpriseId();
                          /*  customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(ordNo,
                                    payOrderInfo.getCustomerPhone(),new BigDecimal(amt),enterpriseId.longValue(),
                                    payOrderInfo.getStationId().longValue(),payType,null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/
                        //计算积分 成长值
                        CalculateIntegral calculateIntegral = new CalculateIntegral();
                        calculateIntegral.setEnterpriseId(enterpriseId);
                        calculateIntegral.setOilId(payOrderInfo.getOilId());
                        calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
                        calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
                        calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
                        calculateIntegral.setUserId(payOrderInfo.getConsumerId());      //此参数用作计算超级会员的积分

                        CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
                        payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(), ordNo);
                        //更新积分，成长值
                        if (StringUtils.isNotBlank(payOrderInfo.getCustomerPhone())) {
                            logger.info("客户手机号：" + payOrderInfo.getCustomerPhone());
                            AppUserInfo appUserInfo = new AppUserInfo();
                            appUserInfo.setStationId(enterpriseId);
                            //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                            appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                            AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                            if (null != userInfo) {
                                logger.info("用户信息原有：成长值" + userInfo.getGrowUpValue() + ";积分：" + userInfo.getIntegral());
                                Integer integral = userInfo.getIntegral();
                                Integer growUpValue = userInfo.getGrowUpValue();
                                logger.info("用户信息本次加油后获得的：成长值" + calIntegral.getGrowValue() + ";积分：" + calIntegral.getIntegral());
                                appUserInfo.setIntegral(calIntegral.getIntegral() + integral);
                                appUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
                                appUserInfoService.updateAppUserIntegral(appUserInfo);


                                //生成积分记录
                                calculateIntegral.setStationId(payOrderInfo.getStationId());
                                calculateIntegral.setNickName(userInfo.getBlogNickName());
                                calculateIntegral.setOrderNo(payOrderInfo.getOrderNo());
                                calculateIntegral.setUnionId(userInfo.getUnionId());
                                calculateIntegral.setMobilePhone(userInfo.getMobilePhone());
                                this.createIntegralRecord(calculateIntegral, payOrder.getPayType(), appUserInfo.getIntegral());

                                //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                                if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                    //修改优惠券状态
                                    if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {

                                        logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                        Map<String, Object> param = new HashMap<>();
                                        param.put("couponUserId", payOrderInfo.getDiscountCoupon());
                                        List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                        if (null != couponUserList && couponUserList.size() == 1) {
                                            couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                            if (null != ct) {
                                                couponService.updateCouponTemplate(CouponTemplate.builder()
                                                        .useCouponNum(ct.getUseCouponNum() + 1)
                                                        .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                        .build());
                                            }
                                        }

//                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
//                                            couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
//                                            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).build());
//                                            if(null != ct){
//                                                couponService.updateCouponTemplate(CouponTemplate.builder()
//                                                        .useCouponNum(ct.getUseCouponNum()+1)
//                                                        .couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon()))
//                                                        .build());
//                                            }
                                    }
                                    int i = couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()), ordNo);
                                    //优惠券主动领取后推送消息
                                    if (i > 0)
                                        couponService.pushWxGzhInitiativeCouponInfo(station, payOrderInfo, i, appUserInfo);
                                }
                                //积分推送
//                                    calculateIntegral.setBlogOpenid(userInfo.getBlogOpenid());
//                                    this.pushIntegralToUser(appUserInfo, station, calculateIntegral);

                                userInfo.setIntegral(userInfo.getIntegral() + calIntegral.getIntegral());
                                userInfo.setGrowUpValue(userInfo.getGrowUpValue() + calIntegral.getGrowValue());
                                gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
                            }

                        } else {
                            logger.info("更新用户积分时，用户手机号不存在");
                        }
                    } else {
                        logger.info("该油站不存在或者油企ID为空");
                    }
                } else {
                    logger.info("更新订单状态失败！");
                }
            }
        } else {
            logger.info("该订单不存在！");
        }
//        }else{
//            logger.info("随行付验签失败");
//            resultJson.put("code","fail");
//            resultJson.put("msg","失败");
//        }
        logger.info("======返回随行付参数信息：" + resultJson.toString());
        return resultJson;
    }

    /*
     * 小程序消费  云闪付扫呗回调
     * @param params
     * @return
     */
    @RequestMapping(value = "/sbPayCallback", consumes = "text/xml", method = RequestMethod.POST)
    @Transactional
    public net.sf.json.JSONObject sbPayCallback(@RequestBody String params) throws ParseException {
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();       //返回
        YunPayCallBack yunPayCallBack = JSON.parseObject(params, YunPayCallBack.class);
        logger.info("========云闪付扫呗回调接口返回参数：" + params);
        if (yunPayCallBack.getResult_code() != null && yunPayCallBack.getResult_code().equals("01")) {
            //返给云闪付状态码
            result.put("return_code", "01");
            result.put("return_msg", "success");
            String ordNo = yunPayCallBack.getTerminal_trace();
            PayOrder payOrderInfo = payOrderMapper.selectOrderInfoByOrdNo(ordNo);
            if (payOrderInfo != null) {
                if (payOrderInfo.getStatus() != null && "0".equals(payOrderInfo.getStatus())) {
                    PayOrder payOrder = new PayOrder();
                    payOrder.setOrderNo(ordNo);
                    payOrder.setStatus("1");
                    double amt = new BigDecimal(yunPayCallBack.getTotal_fee()).divide(new BigDecimal("100")).doubleValue();
                    if (yunPayCallBack.getPay_type().equals("010")) {   //010 微信
                        payOrder.setPayType("wx");
                        payOrder.setWxAmt(amt);
                    } else if (yunPayCallBack.getPay_type().equals("020")) {   //支付宝
                        payOrder.setPayType("zfb");
                        payOrder.setZfbAmt(amt);
                    }
                    payOrder.setDzkAmt(Double.valueOf("0"));
                    //.transactionId(yunPayCallBack.getChannel_trade_no())
                    payOrder.setTransactionId(yunPayCallBack.getChannel_trade_no());
                    //new SimpleDateFormat("yyyyMMddHHmmss").parse(payTime)
                    payOrder.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(yunPayCallBack.getEnd_time()).getTime()));    //支付时间
                    payOrder.setReceivedAmt(amt);                                //settleAmt商家入账金额

                    //修改订单状态
                    int count = payOrderService.getUpdatePayOrder(payOrder);

                    if (count == 1) {
                        logger.info("更新订单状态成功，云闪付扫呗支付完成！");
                        Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
                        if (station != null && station.getEnterpriseId() != null) {
                            Integer enterpriseId = station.getEnterpriseId();

                         /*   customerCardSettingDetailService.calConsumePresentAmtAndCreateRecord(ordNo,
                                    payOrderInfo.getCustomerPhone(),new BigDecimal(amt),enterpriseId.longValue(),
                                    payOrderInfo.getStationId().longValue(),payOrder.getPayType(),null,payOrderInfo.getOilId(),PresentAmountRecord.businessName_payOrder,PresentAmountRecord.purpose_add);
*/

                            //计算积分 成长值
                            CalculateIntegral calculateIntegral = new CalculateIntegral();
                            calculateIntegral.setEnterpriseId(enterpriseId);
                            calculateIntegral.setOilId(payOrderInfo.getOilId());
                            calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
                            calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
                            calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
                            CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
                            payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(), ordNo);
                            //更新成长值，积分
                            if (StringUtils.isNotBlank(payOrderInfo.getCustomerPhone())) {
                                AppUserInfo appUserInfo = new AppUserInfo();
                                appUserInfo.setStationId(enterpriseId);
                                //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                                appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                                AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                                if (null != userInfo) {
                                    Integer integral = userInfo.getIntegral();
                                    Integer growUpValue = userInfo.getGrowUpValue();
                                    appUserInfo.setIntegral(calIntegral.getIntegral() + integral);
                                    appUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
                                    appUserInfoService.updateAppUserIntegral(appUserInfo);

                                    //生成积分记录
                                    calculateIntegral.setStationId(payOrderInfo.getStationId());
                                    calculateIntegral.setNickName(userInfo.getBlogNickName());
                                    calculateIntegral.setOrderNo(payOrderInfo.getOrderNo());
                                    calculateIntegral.setUnionId(userInfo.getUnionId());
                                    calculateIntegral.setMobilePhone(userInfo.getMobilePhone());
                                    this.createIntegralRecord(calculateIntegral, payOrder.getPayType(), appUserInfo.getIntegral());

                                    payOrderInfo.setPayDate(new Timestamp(new SimpleDateFormat("yyyyMMddHHmmss").parse(yunPayCallBack.getEnd_time()).getTime()));
                                    payOrderInfo.setIntegral(calIntegral.getIntegral() + "");
                                    payOrderInfo.setPayType(payOrder.getPayType());
                                    payOrderInfo.setStatus(payOrder.getStatus());
                                    payOrderInfo.setReceivedAmt(payOrder.getReceivedAmt());
                                    //飞鹅打印机 打印
                                    gzhNewsTemplateService.feiePush(payOrderInfo);
                                    gzhNewsTemplateService.pushConsumeToEmployees(payOrderInfo);

                                    //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                                    if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                        //修改优惠券状态
                                        if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {

                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("couponUserId", payOrderInfo.getDiscountCoupon());
                                            List<CouponUser> couponUserList = couponService.selectCouponUserList(param);
                                            if (null != couponUserList && couponUserList.size() == 1) {
                                                couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                                CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(couponUserList.get(0).getCouponTemplateId()).build());
                                                if (null != ct) {
                                                    couponService.updateCouponTemplate(CouponTemplate.builder()
                                                            .useCouponNum(ct.getUseCouponNum() + 1)
                                                            .couponTemplateId(couponUserList.get(0).getCouponTemplateId())
                                                            .build());
                                                }
                                            }

//                                            logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
//                                            couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
//                                            CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).build());
//                                            if(null != ct){
//                                                couponService.updateCouponTemplate(CouponTemplate.builder()
//                                                        .useCouponNum(ct.getUseCouponNum()+1)
//                                                        .couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon()))
//                                                        .build());
//                                            }
                                        }
                                        int i = couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()), ordNo);
                                        //优惠券主动领取后推送消息
                                        if (i > 0)
                                            couponService.pushWxGzhInitiativeCouponInfo(station, payOrderInfo, i, appUserInfo);
                                    }
                                    //积分推送
//                                    calculateIntegral.setBlogOpenid(userInfo.getBlogOpenid());
//                                    calculateIntegral.setEnterpriseId(appUserInfo.getEnterpriseId());
//                                    this.pushIntegralToUser(appUserInfo, station, calculateIntegral);
                                    userInfo.setIntegral(userInfo.getIntegral() + calIntegral.getIntegral());
                                    userInfo.setGrowUpValue(userInfo.getGrowUpValue() + calIntegral.getGrowValue());
                                    gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
                                }
                            } else {
                                logger.info("更新用户积分时，用户手机号不存在");
                            }
                        } else {
                            logger.info("该油站不存在或者油企ID为空");
                        }
                    } else {
                        logger.info("更新订单状态失败！");
                    }
                }
            } else {
                logger.info("该订单不存在！");
            }
        } else {
            result.put("return_code", "02");
            result.put("return_msg", "fail");
        }
        logger.info("=========返给云闪付扫呗结果信息：" + result);
        return result;
    }


    /****
     * 计算积分
     * @return
     */
    public CalculateIntegral calUserIntegral(CalculateIntegral calculateIntegral) {
        int integral = 0;        //普通积分
        int growValue = 0;       //成长值
        int cashIntegral = 0;    //现金积分
        IntegralRule integralRule = new IntegralRule();
        integralRule.setStationId(calculateIntegral.getEnterpriseId());
        integralRule.setOilId(calculateIntegral.getOilId());
        //获取该油站的积分规则
        List<IntegralRule> integralRuleList = integralRuleService.getIntegralRule(integralRule);
        if (integralRuleList != null && integralRuleList.size() > 0) {
//            logger.info("该油站积分规则信息：" + integralRuleList.toString());
            Date emptyDate = integralRuleList.get(0).getEmptyDate();
            //积分规则有效时间 为null时 表示永久有效
            if (emptyDate == null || emptyDate.compareTo(new Date()) == 1 || emptyDate.compareTo(new Date()) == 0) {
                List<IntegralRuleDetail> integralRuleDetailList = integralRuleList.get(0).getIntegralRuleDetailList();
                integralRuleDetailList = integralRuleDetailList.stream().filter(i -> integralRuleService.checkEffectiveTime(i)).collect(Collectors.toList());
                String currentTime = null;          //当前时间
                String datePickerTime = null;         //活动时间
                String[] datePickerTimeArray = {};
                String integralActivity = integralRuleList.get(0).getIntegralActivity();
                String integralProportion = null;
                if (integralActivity != null && integralActivity.equals("1")) {
                    datePickerTime = integralRuleList.get(0).getDatePickerTime();
                    integralProportion = integralRuleList.get(0).getIntegralProportion();
                    if (datePickerTime.contains(",")) {
                        datePickerTimeArray = datePickerTime.split(",");
                    } else {
                        datePickerTimeArray = new String[1];
                        datePickerTimeArray[0] = datePickerTime;
                    }
                }
                if (integralRuleDetailList != null && integralRuleDetailList.size() > 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());   //获取当前时间
                    BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                    BigDecimal multiplyCashIntegral = BigDecimal.ZERO;
                    for (IntegralRuleDetail integralRuleDetail : integralRuleDetailList) {
                        if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("1")) {  //按照实收金额
                            if (calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){      //等级为0时，表示所有人
                                divide = calculateIntegral.getAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                //BigDecimal multiplyGrowValue = BigDecimal.ZERO;
                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        } else if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("2")) {    //按应收金额
                            if (calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getReceivableAmt().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getReceivableAmt().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());

                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":   //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        } else if (StringUtils.isNotBlank(integralRuleDetail.getRuleType()) && integralRuleDetail.getRuleType().equals("3")) {    //按照加油升数
                            if (calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) == 1 || calculateIntegral.getOilLiters().compareTo(integralRuleDetail.getRuleTerms()) == 0) {
                                BigDecimal divide = null;
                                BigDecimal multiply = null;
                                //if(integralRuleDetail.getGread().equals("0")){
                                divide = calculateIntegral.getOilLiters().divide(integralRuleDetail.getSaleAmt(), 0, BigDecimal.ROUND_DOWN);
                                multiply = divide.multiply(integralRuleDetail.getIntegral());
                                if (integralRuleDetail.getGrowValue() != null) {
                                    multiplyGrowValue = divide.multiply(new BigDecimal(integralRuleDetail.getGrowValue().toString()));           //成长值
                                }
                                if (null != integralRuleDetail.getCashIntegral()) {
                                    multiplyCashIntegral = divide.multiply(integralRuleDetail.getCashIntegral());                        //现金积分
                                }
                                if (integralActivity != null && integralActivity.equals("1") && datePickerTimeArray != null && integralProportion != null) {
                                    String datePicker = integralRuleList.get(0).getDatePicker();
                                    switch (datePicker) {
                                        case "1":   //  1.按周来
                                            int day_Week = calendar.get(Calendar.DAY_OF_WEEK);
                                            day_Week = day_Week - 1;     //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_Week);
                                            break;
                                        case "2":  //  2.每月的 多少号
                                            int day_month = calendar.get(Calendar.DAY_OF_MONTH);
                                            day_month = day_month - 1;        //减一原因：数据库存的下标从零开始
                                            currentTime = String.valueOf(day_month); //当前时间
                                            break;
                                        case "3":   //  3.固定日期
                                            currentTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //当前时间
                                            break;
                                    }
                                    for (String s : datePickerTimeArray) {
                                        if (s.equals(currentTime)) {
                                            multiply = multiply.multiply(new BigDecimal(integralProportion));
                                            multiplyGrowValue = multiplyGrowValue.multiply(new BigDecimal(integralProportion));
                                            multiplyCashIntegral = multiplyCashIntegral.multiply(new BigDecimal(integralProportion));
                                            break;
                                        }
                                    }
                                }
                                integral = multiply.intValue();
                                cashIntegral = multiplyCashIntegral.intValue();
                                growValue = multiplyGrowValue.intValue();
                                break;
                                //}
                            }
                        }
                    }
                }
            }
        }
        // 超级会员的逻辑 这里不对呀
        if (null != calculateIntegral.getUserId()) {
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                    .userId(Long.valueOf(calculateIntegral.getUserId()))
                    .enterpriseId(Long.valueOf(calculateIntegral.getEnterpriseId()))
                    .build());
            if (appUserSuperDetails != null && appUserSuperDetails.size() == 1) {
                AppUserSuperDetail appUserSuperDetail = appUserSuperDetails.get(0);
                if (appUserSuperDetail.getBeginDate() != null && appUserSuperDetail.getBeginDate().before(new Date()) && appUserSuperDetail.getEndDate() != null && appUserSuperDetail.getEndDate().after(new Date())) {
                    AppUserSuper appUserSuper = appUserSuperService.selectAppUserSuperById(appUserSuperDetail.getSuperId());
                    if (null != appUserSuper.getMultiple()) {
                        BigDecimal superIntegral = new BigDecimal(integral).multiply(new BigDecimal(appUserSuper.getMultiple().toString()));
                        integral = superIntegral.setScale(0, BigDecimal.ROUND_UP).intValue();
                    }
                }
            }
        }
        calculateIntegral.setIntegral(integral);
        calculateIntegral.setCashIntegral(cashIntegral);
        calculateIntegral.setGrowValue(growValue);
        logger.info("本次客户所得积分：" + integral);
        logger.info("本次客户所得现金积分：" + cashIntegral);
        logger.info("本次客户所得成长值：" + cashIntegral);
        return calculateIntegral;
    }

    /***
     * 生成积分记录
     * @param calculateIntegral
     */
    public void createIntegralRecord(CalculateIntegral calculateIntegral, String payType, Integer totalIntegral) {
        CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
        customerPointsRecord.setCreateTime(new Date());
        if ("xj".equals(payType)) {
            customerPointsRecord.setIntegral(calculateIntegral.getCashIntegral());
        } else {
            customerPointsRecord.setIntegral(calculateIntegral.getIntegral());
        }
        customerPointsRecord.setOrderNo(calculateIntegral.getOrderNo());
        customerPointsRecord.setRecordType("+");
        customerPointsRecord.setMobilePhone(calculateIntegral.getMobilePhone());
        customerPointsRecord.setUnionId(calculateIntegral.getUnionId());
        customerPointsRecord.setStationId(calculateIntegral.getStationId());
        customerPointsRecord.setCustomerName(calculateIntegral.getNickName());
        customerPointsRecord.setAction(integralTypeEnum.REFUEL);
        customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);
        customerPointsRecordService.sendwxgzh(calculateIntegral.getStationId(), calculateIntegral.getMobilePhone(), customerPointsRecord.getIntegral(), totalIntegral, "+");
        logger.info("生成积分记录" + customerPointsRecord.toString());
    }

    /**
     * 积分模板推送
     *
     * @param appUserInfo
     * @param station
     * @param calculateIntegral
     */
    public void pushIntegralToUser(AppUserInfo appUserInfo, Station station, CalculateIntegral calculateIntegral) {
        String gzhAppId = "";
        String gzhAppSecret = "";
        String stationName = "";        //油站名称
        logger.info("客户公众号openId：" + calculateIntegral.getBlogOpenid() + "；油企ID：" + calculateIntegral.getEnterpriseId());
        if (calculateIntegral.getEnterpriseId() != null) {
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(calculateIntegral.getEnterpriseId());
            if (enterprise != null && StringUtils.isNotBlank(enterprise.getGzhAppId()) && StringUtils.isNotBlank(enterprise.getGzhAppSecret())) {
                logger.info("获取油企APPID和秘钥");
                stationName = station.getStationName();
                gzhAppId = enterprise.getGzhAppId();
                gzhAppSecret = enterprise.getGzhAppSecret();
                if (StringUtils.isNotBlank(calculateIntegral.getBlogOpenid())) {
                    GzhNewsTemplate gzhNewsTemplate = new GzhNewsTemplate();
                    gzhNewsTemplate.setStationId(appUserInfo.getStationId());
                    gzhNewsTemplate.setTemplateType("1");
                    GzhNewsTemplate gzhNewsTemplateInfo = gzhNewsTemplateService.getGzhNewsTemplate(gzhNewsTemplate);
                    if (gzhNewsTemplateInfo != null && gzhNewsTemplateInfo.getTemplateId() != null) {
                        logger.info("推送模板ID：" + gzhNewsTemplateInfo.getTemplateId());
                        //推送模板
//                        List<WxMpTemplateData> wxMpTemplate = new ArrayList<>();
//                        wxMpTemplate.add(new WxMpTemplateData("first","尊敬的"+calculateIntegral.getNickName()+"，您好：\n" + "您在"+stationName+"的积分最新交易信息如下"));
//                        wxMpTemplate.add(new WxMpTemplateData("time", new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())));
//                        wxMpTemplate.add(new WxMpTemplateData("type", "增加"));
//                        wxMpTemplate.add(new WxMpTemplateData("Point", String.valueOf(calculateIntegral.getIntegral())));
//                        wxMpTemplate.add(new WxMpTemplateData("From", stationName));
//                        wxMpTemplate.add(new WxMpTemplateData("remark",
//                                "截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date())+"，您在"+stationName+"的可用积分为 "+appUserInfo.getIntegral().toString()+" 分"));
//                        wxPushUtil.push(gzhAppId, gzhAppSecret, gzhNewsTemplateInfo.getTemplateId(), calculateIntegral.getBlogOpenid(), wxMpTemplate);

                        //新修订
                        WxTemplateMsg wxTemplateMsg = new WxTemplateMsg();
                        wxTemplateMsg.setTemplate_id(gzhNewsTemplateInfo.getTemplateId());
                        wxTemplateMsg.setTouser(calculateIntegral.getBlogOpenid());
                        Map<String, WxTemplateData> templateDataMap = new HashMap<>();
                        templateDataMap.put("first", WxTemplateData.builder().value("尊敬的" + calculateIntegral.getNickName() + "您好：" + "您在" + stationName + "的积分最新交易信息如下").build());
                        templateDataMap.put("time", WxTemplateData.builder().value(new SimpleDateFormat("yyyy年MM月dd日HH时mm分").format(new Date())).build());
                        templateDataMap.put("type", WxTemplateData.builder().value("增加").build());
                        templateDataMap.put("Point", WxTemplateData.builder().value(String.valueOf(calculateIntegral.getIntegral())).build());
                        templateDataMap.put("From", WxTemplateData.builder().value(stationName).build());
                        templateDataMap.put("remark", WxTemplateData.builder().value("截止至" + new SimpleDateFormat(" yyyy年MM月dd日HH时mm分").format(new Date()) + "，您在" + stationName + "的可用积分为 " + appUserInfo.getIntegral().toString() + " 分").build());
                        wxTemplateMsg.setData(templateDataMap);
                        wxPushUtil.sendTemplateMsg(gzhAppId, gzhAppSecret, wxTemplateMsg);
                        logger.info("消息推送完成");
                    }
                }
            }
        }
    }

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public void test() {
        try {
            throw new Exception("你好");
        } catch (Exception e) {
            logger.error("哈哈哈哈哈", e);
            System.out.println(e.getMessage());
            String ea = e.getStackTrace().toString();
            logger.error(e.getStackTrace().toString());
        }
    }

    /*
     * 根据用户unionId、油站ID或油企ID查询用户订单（消费记录）
     * @param unionId
     * @param enterpriseId
     * @param pageSize
     * @param pageNum
     * @param stationId
     * @return
     */
    @GetMapping(value = "/getUserOrderListByUnionId")
    @ApiOperation(value = "根据用户unionId、油站ID或油企ID查询用户订单（消费记录）", httpMethod = "GET", notes = "根据用户unionId、stationId或油企ID查询用户订单（消费记录）")
    public String getUserOrderListByUnionId(@RequestParam String mobilePhone,
                                            @RequestParam Integer enterpriseId,
                                            @RequestParam Integer pageSize,
                                            @RequestParam Integer pageNum,
                                            Integer stationId,
                                            String oilName) {
        logger.info("getUserOrderListByUnionId 请求参数 mobilePhone：[{}],enterpriseId:[{}]", mobilePhone, enterpriseId);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(mobilePhone) && enterpriseId != null) {
            AppUserInfo appUserInfo = new AppUserInfo();
            //appUserInfo.setUnionId(unionId);
            appUserInfo.setMobilePhone(mobilePhone);
            if (pageSize != null && pageNum != null) {
                if (stationId != null) {
                    appUserInfo.setStaJiBie("2");
                    appUserInfo.setStationId(stationId);
                } else {
                    appUserInfo.setStaJiBie("1");
                    appUserInfo.setStationId(enterpriseId);
                }
                if (StringUtils.isNotBlank(oilName)) {
                    appUserInfo.setOilName(oilName);
                }
//                AppUserInfo form = new AppUserInfo();
//                form.setMobilePhone(mobilePhone);
//                form.setStationId(enterpriseId);
//                List<AppUserInfo> userInfos = appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(form);
//                if (!userInfos.isEmpty()) {
//                    appUserInfo.setMobilePhone(null);
//                    appUserInfo.setUserId(userInfos.get(0).getUserId());
//                }

                List<PayOrder> payOrderList = payOrderService.getUserOrderListByMobilePhone(appUserInfo);
                for (PayOrder payOrderItem : payOrderList) {
                    BigDecimal originalAmt = payOrderItem.getOriginalAmt();
                    if (originalAmt != null) {
                        payOrderItem.setAmt(originalAmt.doubleValue());
                        payOrderItem.setReceivedAmt(originalAmt.doubleValue());
                    }
                }
                // 手动分页
                PageInfo pageInfo = PageInfoUtil.listPageInfo(pageNum, pageSize, payOrderList);
                resultData = ResultData.success(pageInfo);
            } else {
                resultData = ResultData.error(CodeMsg.PARAMS_NUll);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    /*
     * 根据订单号获取订单信息
     * @RequestBody String orderno
     * @param orderNo
     * @return
     */
    @GetMapping(value = "/selectOrderInfoByOrdNo")
    @ApiOperation(value = "根据订单号获取订单信息", httpMethod = "GET", notes = "根据订单号获取订单信息")
    public String getPayOrderList(@RequestParam String orderNo) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(orderNo)) {
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(orderNo);
            BigDecimal originalAmt = payOrder.getOriginalAmt();
            if (originalAmt != null) {
                payOrder.setAmt(originalAmt.doubleValue());
                payOrder.setReceivedAmt(originalAmt.doubleValue());
            }
            resultData = ResultData.success(payOrder);
        } else {
            resultData = ResultData.error(CodeMsg.SEARCH_FAIL);
        }
        return gson.toJson(resultData);
    }


//    /*
//     * 根据订单号获取订单信息
//     * @RequestBody String orderno
//     * @param orderNo
//     * @return
//     */
//    @GetMapping(value = "/selectOrderInfoByUuid")
//    @ApiOperation(value = "根据订单号获取订单信息", httpMethod = "GET", notes = "根据订单号获取订单信息")
//    public String selectOrderInfoByUuid(@RequestParam String uuid){
//        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
//        ResultData resultData =null;
//        if(StringUtils.isNotBlank(uuid)){
//            PayOrder payOrder = payOrderService.selectOrderInfoByUuid(uuid);
//            BigDecimal originalAmt = payOrder.getOriginalAmt();
//            if (originalAmt != null) {
//                payOrder.setAmt(originalAmt.doubleValue());
//                payOrder.setReceivedAmt(originalAmt.doubleValue());
//            }
//            resultData = ResultData.success(payOrder);
//        }else {
//            resultData=ResultData.error(CodeMsg.SEARCH_FAIL);
//        }
//        return gson.toJson(resultData);
//    }


//    @GetMapping(value = "/selectOrderCouponCountByOrdNo")
//    @ApiOperation(value = "根据手机号获取优惠券数量", httpMethod = "GET", notes = "根据手机号获取优惠券数量")
//    public String selectOrderCouponCountByOrdNo(@RequestParam String orderNo){
//        Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
//        ResultData resultData =null;
//
//        int couponCount = payOrderService.selectOrderCouponCountByOrdNo(orderNo);
//        resultData = ResultData.success(couponCount);
//        return gson.toJson(resultData);
//    }


    //现金或刷卡银联支付 pos机上
    @PostMapping(value = "createCashOrUnionPayOrder")
    @ApiOperation(value = "现金支付创建订单", httpMethod = "POST")
    @Transactional
    public String createCashOrUnionPayOrder(@RequestBody PayOrderRequest payOrderRequest) {
        logger.info("/createCashOrUnionPayOrder");
        logger.info(payOrderRequest.toString());
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (null != payOrderRequest.getStationId() && StringUtils.isNotBlank(payOrderRequest.getGunName()) && StringUtils.isNotBlank(payOrderRequest.getPayType())
                && StringUtils.isNotBlank(payOrderRequest.getOrderOriginType()) && StringUtils.isNotBlank(payOrderRequest.getReceivableAmt())) {
            Station stationInfo = enterpriseService.selectStationById(payOrderRequest.getStationId());
            if (null != stationInfo) {
                if (StringUtils.isBlank(payOrderRequest.getUtmSource())) {
                    // 订单来源默认9
                    payOrderRequest.setUtmSource("9");
                }
                PayOrder payOrder = new PayOrder();
                payOrder.setPayType(payOrderRequest.getPayType());
                payOrder.setOrderOriginType(payOrderRequest.getOrderOriginType());  //订单来源
                payOrder.setOrderRandomId(payOrderRequest.getOrderRandomId());      //POS机随机号
                payOrder.setOilPersonnelId(payOrderRequest.getUserId());     //加油员ID
                payOrder.setStationName(stationInfo.getStationName());
                payOrder.setUtmSource(payOrderRequest.getUtmSource());
                Random random = new Random();
                String result = "";
                for (int i = 0; i < 6; i++) {
                    result += random.nextInt(10);
                }
                String ordNo = System.currentTimeMillis() + result;
                payOrder.setOrderNo(ordNo);                                             //订单号
                logger.info("生成的订单号：" + ordNo);
                payOrder.setStationId(payOrderRequest.getStationId());
                payOrder.setEnterpriseId(stationInfo.getEnterpriseId());
                //油站id
                payOrder.setCreatedDate(new Timestamp(new Date().getTime()));


                //payOrder.setStatus("1");                                              //创建订单 未支付状态 0
                payOrder.setOilGun(payOrderRequest.getGunName());                       //油枪号

                //油品价格
                StaOilGun staOilGun = new StaOilGun();
                staOilGun.setGunName(payOrderRequest.getGunName());
                staOilGun.setStationId(payOrderRequest.getStationId());
                StaOilGun staOilGunInfo = enterpriseService.selectStaGunInfo(staOilGun);
                BigDecimal oilStationPrice = staOilGunInfo.getOilStationPrice();
                String oilPrice = oilStationPrice.toString();                    //油站油品价格
                payOrder.setOilPirce(oilPrice);
                payOrder.setOrderType(staOilGunInfo.getOil().getOilClass());        //订单类型

                //油品名称
                payOrder.setOilName(staOilGunInfo.getOilId().toString());
                //应收金额
                payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));

                //优惠金额
                payOrder.setDiscountAmt(Double.valueOf("0.00"));
                //加油升数
                BigDecimal oilLiters = new BigDecimal(payOrderRequest.getReceivableAmt()).divide(new BigDecimal(oilPrice), 4, BigDecimal.ROUND_HALF_UP);
                payOrder.setOrderLiters(oilLiters.toString());
                payOrder.setReceivableAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));      //订单应收金额
                payOrder.setWxAmt(Double.valueOf(0));
                payOrder.setZfbAmt(Double.valueOf(0));
                payOrder.setDzkAmt(Double.valueOf(0));


                //计算立减
                ReductionActivitiesVO activitiesVO = null;
                //优惠金额
                BigDecimal discountAmt = BigDecimal.ZERO;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                BigDecimal amt = new BigDecimal(payOrder.getAmt());
                BigDecimal originalAmt = new BigDecimal(payOrder.getAmt());
                if (payOrderRequest.getEnableDiscount() == null || payOrderRequest.getEnableDiscount()) {
                    //订单立减活动优惠
                    activitiesVO = new ReductionActivitiesVO();
                    activitiesVO.setActivityUse("CSP");
                    activitiesVO.setAmt(new BigDecimal(payOrder.getAmt()));
                    activitiesVO.setDateTime(sdf.format(new Date()));
                    activitiesVO.setEnterpriseId(stationInfo.getEnterpriseId());
                    activitiesVO.setOilId(staOilGunInfo.getOilId());
                    activitiesVO.setOrderLiters(oilLiters.toString());
                    activitiesVO.setStationId(payOrderRequest.getStationId());
                    activitiesVO.setPaymentMethod(payOrderRequest.getPayType());
                    // 抓不到用户信息的默认老用户
                    activitiesVO.setMemberCategory(Constant.MEMBER_CATEGORY_OLD_USER);
                    String cdkMemberMobilePhone = null;
                    if (StringUtils.equals(PayTypeEnum.cdk.getType(), payOrderRequest.getPayType())) {
                        // 车队卡判断新老用户
                        if (StringUtils.isEmpty(payOrderRequest.getCardNumber()))
                            throw new CustomException("车队卡支付方式需要车队卡卡号", 1001);

                        FleetCard fleetCard = fleetCardService.selectFleetCardByCardNumber(payOrderRequest.getCardNumber());
                        if (fleetCard == null) {
                            FleetCardSubVo fleetCardSubVo = fleetCardSubService.selectFleetSubCardByCardNumber(payOrderRequest.getCardNumber());
                            if (fleetCardSubVo == null) {
                                throw new CustomException("车队卡不存在", 1001);
                            } else if (fleetCardSubVo.getAppUserId() != null) {
                                AppUserInfo appUserInfo = appUserInfoMapper.getAppUserById(fleetCardSubVo.getAppUserId());
                                if (appUserInfo != null) {
                                    cdkMemberMobilePhone = appUserInfo.getMobilePhone();
                                }
                            }
                        } else {
                            cdkMemberMobilePhone = fleetCard.getPhone();
                        }
                        if (StringUtils.isNotEmpty(cdkMemberMobilePhone)) {
                            AppUserInfo form = new AppUserInfo();
                            form.setStationId(stationInfo.getEnterpriseId());
                            form.setMobilePhone(cdkMemberMobilePhone);
                            AppUserInfo userInfo = appUserInfoService.getAppUserInfo(form);
                            if (userInfo != null) {
                                Integer orderId = reductionActivityService.getUserOrderId(userInfo);
                                if (orderId != null) {
                                    activitiesVO.setMemberCategory(Constant.MEMBER_CATEGORY_OLD_USER);
                                } else {
                                    activitiesVO.setMemberCategory(Constant.MEMBER_CATEGORY_NEW_USER);
                                }
                                String userGrade = "0";
                                Grade grade = new Grade();
                                grade.setGradeGrowValue(userInfo.getGrowUpValue());
                                grade.setEnterpriseId(Long.valueOf(stationInfo.getEnterpriseId()));
                                grade.setDeleteFlag("0");
                                List<Grade> grades = gradeMapper.selectUserGrade(grade);
                                //logger.info("grades===={}",grades);
                                if (grades != null && grades.size() == 1) {
                                    if (grades.get(0).getGradeCode() != null) userGrade = grades.get(0).getGradeCode();
                                }
                                activitiesVO.setMemberLevel(userGrade);
                                // 判断是不是超级会员
                                Date now = new Date();
                                List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailMapper.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                                        .enterpriseId(Long.valueOf(stationInfo.getEnterpriseId()))
                                        .userId(Long.valueOf(userInfo.getUserId()))
                                        .beginDate(now)
                                        .endDate(now)
                                        .build());
                                if (appUserSuperDetails != null && appUserSuperDetails.size() == 1) {
                                    //有记录，是超级会员
                                    AppUserSuper appUserSuper = appUserSuperMapper.selectAppUserSuperById(appUserSuperDetails.get(0).getSuperId());
                                    if (appUserSuper != null) {
                                        activitiesVO.setSuperUser(ReductionActivityServiceImpl.MEMBER_LEVEL_MAP.get(appUserSuper.getSuperName()));
                                    }
                                    //appUserInfos.setSuperUser(Constant.MEMBER_LEVEL_SUPER);
                                } else {
                                    // 不是
                                    activitiesVO.setSuperUser(null);
                                }
                            }
                        }
                    }
                    discountAmt = payOrderService.reductionActivitiesAmountCalculation(activitiesVO, cdkMemberMobilePhone).setScale(2, BigDecimal.ROUND_HALF_UP);
                    amt = amt.subtract(discountAmt);//计算参与活动之后的实付款金额
                    if (amt.compareTo(DecimalConstant.O_01) <= 0) {
                        amt = DecimalConstant.O_01;
                        discountAmt = originalAmt.subtract(amt);
                    }
                    if (activitiesVO.getActivityId() != null) {
                        //更新活动的预算，避免多个用户同时支付时，产生超预算的问题
                        reductionActivityService.updateReductionActivityBudget(discountAmt.negate(), activitiesVO.getActivityId() == null ? -1 : activitiesVO.getActivityId());
                    }
                }
                payOrder.setAmt(amt.doubleValue());
                payOrder.setDiscountAmt(discountAmt.doubleValue());
                payOrder.setConsumeDiscountAmt(discountAmt);
                payOrder.setRechargeDiscountAmt(BigDecimal.ZERO);

                switch (payOrderRequest.getPayType()) {
                    case "xj":  //现金支付
                        payOrder.setStatus("1");
                        payOrder.setXjAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setConsumer("线下支付");       //客户昵称
                        payOrder.setPayDate(new Timestamp(new Date().getTime()));    //支付时间
                        break;
                    case "cdk":  //车队卡支付
                        //
                        String cdkPayKey = payOrderRequest.getCdkPayKey();
                        if (StringUtils.isNotEmpty(cdkPayKey) && cdkPayKey.contains("_entertime_")) {
                            if (redisCacheUtil.hasKey(cdkPayKey)) {
                                throw new CustomException("请勿重复提交");
                            }
                        }

                        payOrder.setStatus("1");
                        payOrder.setAppType("3"); // pos机
                        payOrder.setXjAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setPayDate(new Timestamp(new Date().getTime()));    //支付时间
                        break;
                    case "hyk":
                        payOrder.setStatus("1");
                        payOrder.setXjAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setConsumer("会员卡支付");       //客户昵称
                        if (StringUtils.isNotBlank(payOrderRequest.getCustomerName()))
                            payOrder.setConsumer(payOrderRequest.getCustomerName());
                        payOrder.setPayDate(new Timestamp(new Date().getTime()));    //支付时间
                        break;
                    case "yl":  //银联刷卡
                        payOrder.setStatus("1");
                        payOrder.setReceivableAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setReceivedAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
                        payOrder.setConsumer("银联刷卡");
                        payOrder.setPayDate(new Timestamp(new Date().getTime()));
                        payOrder.setConsumer("刷卡支付");       //客户昵称
                        break;
                }

                if (payOrderRequest.getPayType().equals("cdk")) {
                    if (StringUtils.isEmpty(payOrderRequest.getCardNumber()))
                        throw new CustomException("车队卡支付方式需要车队卡卡号", 1001);

                    synchronized (this) {
                        FleetCard fleetCard = fleetCardService.selectFleetCardByCardNumber(payOrderRequest.getCardNumber());
                        if (fleetCard == null) {
                            FleetCardSubVo fleetCardSubVo = fleetCardSubService.selectFleetSubCardByCardNumber(payOrderRequest.getCardNumber());
                            if (fleetCardSubVo == null) {
                                throw new CustomException("车队卡不存在", 1001);
                            }
                            //如果用子卡支付
                            Long fleetCardId = fleetCardSubVo.getFleetCardId();
                            fleetCard = fleetCardService.selectById(fleetCardId);
                            //设置子卡id
                            fleetCard.setFleetCardSubId(fleetCardSubVo.getId());
                            Integer secondaryCardAllocationType = fleetCard.getSecondaryCardAllocationType();
                            if (secondaryCardAllocationType.equals(FleetCard.USE_TYPE_SHARE)) {
                                //如果是共享主卡
                                payOrder = fleetCardService.cdkPay(fleetCard, stationInfo, payOrder);
                                payOrder.setCdkId(fleetCardSubVo.getId());
                                payOrder.setCdkType(FleetCard.cdkType_fleet_card_sub);
                                AppUserInfo appUserById = appUserInfoMapper.getAppUserById(fleetCardSubVo.getAppUserId());
                                if (appUserById != null) {
                                    payOrder.setCustomerPhone(appUserById.getMobilePhone());
                                }
                            } else if (secondaryCardAllocationType.equals(FleetCard.USE_TYPE_ALLOCATION)) {
                                //如果是手动分配
                                payOrder = fleetCardSubService.cdkSubPay(fleetCardSubVo, stationInfo, payOrder);
                            } else {
                                throw new CustomException("未配置子卡额度");
                            }
                        } else {
                            //如果用主卡支付
                            payOrder = fleetCardService.cdkPay(fleetCard, stationInfo, payOrder);
                        }
                    }
                }


                //积分增加
                if (StringUtils.isNotBlank(payOrderRequest.getMemberCode())) {
                    String customerPhone = payOrderRequest.getCustomerPhone();
                    AppUserInfo userInfo = new AppUserInfo();
                    userInfo.setStationId(stationInfo.getEnterpriseId());
                    //userInfo.setMobilePhone(customerPhone);
                    userInfo.setMemberCode(payOrderRequest.getMemberCode());
                    //根据会员码获取用户信息
                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfoByMemberCode(userInfo);
                    if (null != appUserInfo) {
                        //如果系统已存在用户
                        Integer integral = appUserInfo.getIntegral();
                        Integer growUpValue = appUserInfo.getGrowUpValue();
                        payOrder.setConsumerId(appUserInfo.getUserId());
                        payOrder.setConsumer(appUserInfo.getBlogNickName());
                        CalculateIntegral calculateIntegral = new CalculateIntegral();
                        calculateIntegral.setEnterpriseId(stationInfo.getEnterpriseId());
                        calculateIntegral.setOilName(staOilGunInfo.getOil().getOilName());
                        calculateIntegral.setOilId(staOilGunInfo.getOilId());
                        calculateIntegral.setOilLiters(new BigDecimal(payOrder.getOrderLiters()));
                        calculateIntegral.setReceivableAmt(new BigDecimal(payOrder.getReceivableAmt()));
                        calculateIntegral.setAmt(new BigDecimal(payOrder.getAmt()));
                        //计算积分、成长值
                        CalculateIntegral calResult = this.calUserIntegral(calculateIntegral);
                        payOrderService.updateGrowthValueByOrdNo(calResult.getGrowValue().longValue(), ordNo);
                        //更新用户积分、成长值
                        appUserInfo.setGrowUpValue(growUpValue + calResult.getGrowValue());
                        appUserInfo.setIntegral(integral + calResult.getCashIntegral());
                        appUserInfo.setUpdateDate(new Date());
                        appUserInfoService.updateAppUserIntegral(appUserInfo);

                        //生成积分记录
                        calculateIntegral.setUnionId(appUserInfo.getUnionId());
                        calculateIntegral.setStationId(payOrderRequest.getStationId());
                        calculateIntegral.setNickName(appUserInfo.getBlogNickName());
                        calculateIntegral.setOrderNo(ordNo);
                        calculateIntegral.setMobilePhone(appUserInfo.getMobilePhone());
                        this.createIntegralRecord(calculateIntegral, payOrderRequest.getPayType(), appUserInfo.getIntegral());

                        //推送积分
//                        this.pushIntegralToUser(appUserInfo, stationInfo, calculateIntegral);
                        gzhNewsTemplateService.pushConsumeToUser(appUserInfo, payOrder, calResult.getIntegral());

                    } else {
                        //如果系统不存在此用户，则将客户昵称存入用户手机号
                        payOrder.setConsumer("线下用户");
                    }
                }
                PayOrderHandle.setPayOrderInvoiceStatus(payOrder);
                payOrderMapper.insertSelective(payOrder);
//                gzhNewsTemplateService.feiePush(payOrder);
                PayOrder po = payOrderService.selectOrderInfoByOrdNo(payOrder.getOrderNo());
                if (payOrderRequest.getPayType().equals("cdk")) {
                    //用于车队卡查订单结果
                    String cdkPayKey = payOrderRequest.getCdkPayKey();
                    if (StringUtils.isNotEmpty(cdkPayKey) && cdkPayKey.contains("_entertime_")) {
                        //如果包含时间戳  缓存订单id
                        redisCacheUtil.setCacheObject(cdkPayKey, po.getOrderId(), 15, TimeUnit.SECONDS);
                    }
                    // 车队卡支付pay_order表里的consumer_id不是app_user_info表里的id，所以关联不到手机号
                    // 判断手机号为空设置为pay_order表里的手机号
                    po.setMobilePhone(MobilePhoneUtil.encryPhone(payOrder.getCustomerPhone()));
                }
                if (po.getMobilePhone() == null) {
                    po.setMobilePhone("--");
                }
                resultData = ResultData.success(po);
            } else {
                resultData = ResultData.error(CodeMsg.STATION_NULL_INFO);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }


    /*
     * 小程序现金支付
     * @param payOrderRequest
     * @return
     */
    @GetMapping("/payAppCashOrder")
    @ApiOperation(value = "小程序现金支付")
    @Transactional
    public String payAppCashOrder(@RequestParam String ordNo, String couponUserId) {
        Gson gson = new Gson();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(ordNo)) {
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (null != payOrder) {
                PayOrder p = new PayOrder();
                p.setOrderNo(ordNo);
                //计算使用优惠券后的金额 与优惠券优惠金额
                if (StringUtils.isNotBlank(couponUserId)) {
                    logger.info("小程序现金支付用户使用的优惠券ID：" + couponUserId);
                    //油站信息
                    Station station = enterpriseService.selectStationById(Integer.valueOf(payOrder.getStationId()));
                    //用户信息
                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().stationId(station.getEnterpriseId()).mobilePhone(payOrder.getCustomerPhone()).build());
                    //计算使用优惠券后传参优惠券ID
                    payOrder.setDiscountCoupon(couponUserId);
                    //计算优惠券
                    CouponUser couponUser = reductionActivityService.checkCoupon(appUserInfo, payOrder, station);
                    logger.info("小程序现金支付用户使用的优惠券信息：" + couponUser);
                    if (null != couponUser) {
                        //使用优惠券时要更新的订单信息
                        p.setDiscountCoupon(couponUserId);
                        p.setDiscountCouponAmt(couponUser.getCouponAmtByCNY().doubleValue());
                        p.setAmt(Double.valueOf(couponUser.getNewAmtByCoupon().toString()));
                        logger.info("小程序现金支付用户要付款的金额：" + couponUser.getNewAmtByCoupon().toString());
                    }
                }
                p.setPayType("xj");
                p.setXJStatus("0");
                payOrderService.getUpdatePayOrder(p);
                resultData = ResultData.success(CodeMsg.SUCCESS);
            } else {
                resultData = ResultData.success(CodeMsg.NO_PAY_ORDER);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    /*
     * 轮询 小程序现金支付订单状态
     * @param payOrderRequest
     * @return
     */
    @GetMapping("/selectCashOrderStatus")
    @ApiOperation(value = "轮询 小程序现金支付订单状态")
    @Transactional
    public String selectCashOrderStatus(@RequestParam String ordNo) {
        Gson gson = new Gson();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(ordNo)) {
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (null != payOrder) {
                resultData = ResultData.success(payOrder);
            } else {
                resultData = ResultData.error(CodeMsg.NO_PAY_ORDER);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    /*
     * 小程序取消现金支付订单
     * @param payOrderRequest
     * @return
     */
    @GetMapping("/cancelCashOrder")
    @ApiOperation(value = "小程序取消现金支付订单")
    @Transactional
    public String cancelCashOrder(@RequestParam String ordNo) {
        Gson gson = new Gson();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(ordNo)) {
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(ordNo);
            if (null != payOrder && "0".equals(payOrder.getStatus())) {
                payOrderService.getUpdatePayOrder(PayOrder.builder().orderNo(ordNo).xJStatus("1").build());
                resultData = ResultData.success(CodeMsg.SUCCESS);
            } else if (null != payOrder && "1".equals(payOrder.getStatus())) {
                resultData = ResultData.error(CodeMsg.ALREADY_PAY);
            } else {
                resultData = ResultData.error(CodeMsg.NO_ORDER);
            }

        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }


    /*
     * 小程序现金支付pos修改订单状态
     * @param payOrderRequest
     * @return
     */
    @PostMapping("/posUpdateOrderStatus")
    @ApiOperation(value = "pos修改订单状态")
    @Transactional
    public String posUpdateOrderStatus(@RequestBody PosUpdateOrderStatus puos) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        logger.info("订单号：" + puos.getOrdNo());
        if (StringUtils.isNotBlank(puos.getOrdNo()) && StringUtils.isNotBlank(puos.getButton()) && StringUtils.isNotBlank(puos.getUserId())) {
            String orderNo = puos.getOrdNo();
            String userId = puos.getUserId();
            PayOrder payOrder = payOrderService.selectOrderInfoByOrdNo(orderNo);
            if (null != payOrder) {
                SysUser sysUser = posMachineService.selectUserByUserId(userId);
                if (null != sysUser) {
                    if (sysUser.getStatus().equals("0")) {
                        if (StringUtils.isNotBlank(sysUser.getUserLeval()) && "2".equals(sysUser.getUserLeval())) {
                            //String stationId = sysUser.getStationId();
                            if (sysUser.getStationId().equals(payOrder.getStationId().toString())) {
                                //1.判断是否是小程序app现金支付订单；
                                if ("0".equals(payOrder.getStatus())) {
                                    if (null != payOrder.getXJStatus() && "0".equals(payOrder.getXJStatus())) {
                                        //2.更新订单状态
                                        if ("1".equals(puos.getButton())) {
                                            payOrderService.getUpdatePayOrder(PayOrder.builder()
                                                    .xjAmt(payOrder.getAmt())
                                                    .wxAmt(Double.valueOf(0))
                                                    .dzkAmt(Double.valueOf(0))
                                                    .zfbAmt(Double.valueOf(0))
                                                    .orderNo(orderNo)
                                                    .deviceNo(puos.getDeviceNo())
                                                    .status("1")
                                                    .payDate(new Timestamp(new Date().getTime()))
                                                    .build());
                                            //更新成功，查询新更新订单信息
                                            PayOrder payOrderInfo = payOrderService.selectOrderInfoByOrdNo(orderNo);
                                            if ("1".equals(payOrderInfo.getStatus())) {
                                                //更新用户积分
                                                Station station = enterpriseService.selectStationById(payOrderInfo.getStationId());
                                                if (station != null && station.getEnterpriseId() != null) {
                                                    Integer enterpriseId = station.getEnterpriseId();
                                                    //计算积分 成长值
                                                    CalculateIntegral calculateIntegral = new CalculateIntegral();
                                                    calculateIntegral.setEnterpriseId(enterpriseId);
                                                    calculateIntegral.setOilId(payOrderInfo.getOilId());
                                                    calculateIntegral.setAmt(new BigDecimal(payOrderInfo.getAmt().toString()));
                                                    calculateIntegral.setReceivableAmt(new BigDecimal(payOrderInfo.getReceivableAmt()));
                                                    calculateIntegral.setOilLiters(new BigDecimal(payOrderInfo.getOrderLiters()));
                                                    CalculateIntegral calIntegral = this.calUserIntegral(calculateIntegral);
                                                    payOrderService.updateGrowthValueByOrdNo(calIntegral.getGrowValue().longValue(), orderNo);
                                                    //更新积分，成长值
                                                    if (StringUtils.isNotBlank(payOrderInfo.getCustomerPhone())) {
                                                        logger.info("客户手机号：" + payOrderInfo.getCustomerPhone());
                                                        AppUserInfo appUserInfo = new AppUserInfo();
                                                        appUserInfo.setStationId(enterpriseId);
                                                        //appUserInfo.setUnionId(payOrderInfo.getUnionId());
                                                        appUserInfo.setMobilePhone(payOrderInfo.getCustomerPhone());
                                                        AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                                                        if (null != userInfo) {
                                                            //小程序现金支付获取积分与支付宝微信走相同方式!!!!!!
                                                            logger.info("用户信息原有：成长值" + userInfo.getGrowUpValue() + ";积分：" + userInfo.getIntegral());
                                                            Integer integral = userInfo.getIntegral();
                                                            Integer growUpValue = userInfo.getGrowUpValue();
                                                            logger.info("用户信息本次加油后获得的：成长值" + calIntegral.getGrowValue() + ";积分：" + calIntegral.getIntegral());
                                                            appUserInfo.setIntegral(calIntegral.getIntegral() + integral);
                                                            appUserInfo.setGrowUpValue(calIntegral.getGrowValue() + growUpValue);
                                                            appUserInfoService.updateAppUserIntegral(appUserInfo);

                                                            //生成积分记录
                                                            calculateIntegral.setStationId(payOrderInfo.getStationId());
                                                            calculateIntegral.setNickName(userInfo.getBlogNickName());
                                                            calculateIntegral.setOrderNo(payOrderInfo.getOrderNo());
                                                            calculateIntegral.setUnionId(userInfo.getUnionId());
                                                            calculateIntegral.setMobilePhone(userInfo.getMobilePhone());
                                                            //小程序现金支付获取积分与支付宝微信走相同方式!!!!!!
                                                            this.createIntegralRecord(calculateIntegral, "wx", appUserInfo.getIntegral());

                                                            //根据油企是否开启优惠券功能，修改优惠券状态和主动领取优惠券
                                                            if (null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())) {
                                                                //修改优惠券状态
                                                                if (StringUtils.isNotBlank(payOrderInfo.getDiscountCoupon())) {
                                                                    logger.info("用户所用优惠券Id：" + payOrderInfo.getDiscountCoupon());
                                                                    couponService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).couponUserId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).couponIsUsed("1").build());
                                                                    CouponTemplate ct = couponService.selectCouponTemInfoById(CouponTemplate.builder().couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon())).build());
                                                                    if (null != ct) {
                                                                        couponService.updateCouponTemplate(CouponTemplate.builder()
                                                                                .useCouponNum(ct.getUseCouponNum() + 1)
                                                                                .couponTemplateId(Integer.valueOf(payOrderInfo.getDiscountCoupon()))
                                                                                .build());
                                                                    }
                                                                }
                                                                couponService.initiativeCoupon(userInfo, station.getStationId(), new BigDecimal(payOrderInfo.getReceivableAmt().toString()), orderNo);
                                                            }
                                                            logger.info("=========================================小程序现金支付完成！===============================================================");
                                                            //积分推送
//                                                            calculateIntegral.setBlogOpenid(userInfo.getBlogOpenid());
//                                                            this.pushIntegralToUser(appUserInfo, station, calculateIntegral);
                                                            gzhNewsTemplateService.pushConsumeToUser(userInfo, payOrderInfo, calIntegral.getIntegral());
                                                        }
                                                    } else {
                                                        logger.info("更新用户积分时，用户手机号不存在");
                                                    }
                                                } else {
                                                    logger.info("该油站不存在或者油企ID为空");
                                                }
                                                resultData = ResultData.success(payOrderInfo);
                                            } else {
                                                resultData = ResultData.error(CodeMsg.CASH_ORDER_CANCEL);
                                            }
                                        } else if ("0".equals(puos.getButton())) {
                                            payOrderService.getUpdatePayOrder(PayOrder.builder().orderNo(orderNo).deviceNo(puos.getDeviceNo()).xJStatus("1").build());
                                            resultData = ResultData.success(CodeMsg.SUCCESS);
                                        }
                                    } else {
                                        resultData = ResultData.error(CodeMsg.CANCEL_CASH_ORDER);
                                    }
                                } else {
                                    resultData = ResultData.error(CodeMsg.NOT_CASH_ORDER_TYPE);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.STATION_ORDER_ID_FIT);
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.USERNAME_LEVEL_ERROR);
                        }
                    } else if (sysUser.getStatus().equals("1")) {
                        resultData = ResultData.error(CodeMsg.ACCOUNT_DISABLE);
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
                }

            } else {
                resultData = ResultData.error(CodeMsg.NO_PAY_ORDER);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    @GetMapping("/order/payTypes")
    @ApiOperation(value = "查询除固定支付方式之外用户自定义的支付方式")
    public ResultData getOrderPayTypes(@RequestParam("stationId") Long stationId) {
        if (Objects.isNull(stationId)) {
            return ResultData.error("请求参数异常");
        }
        log.info("查询除固定支付方式之外用户自定义的支付方式请求参数：[{}]", stationId);
        List<OrderPayType> orderPayTypes = orderPayTypeService.selectOrderPayType(stationId);
        return ResultData.success(orderPayTypes);
    }

    @PostMapping(value = "/createCashOrderPayType")
    @ApiOperation(value = "油站定义支付方式生成订单入口", httpMethod = "POST")
    @Transactional
    public ResultData createCashOrderPayType(@RequestBody PayOrderRequest payOrderRequest) {

        if (Objects.isNull(payOrderRequest.getStationId()) || StringUtils.isEmpty(payOrderRequest.getGunName())
                || StringUtils.isEmpty(payOrderRequest.getPayType()) || StringUtils.isEmpty(payOrderRequest.getOrderOriginType())
                || StringUtils.isEmpty(payOrderRequest.getReceivableAmt())) {
            return ResultData.error(CodeMsg.PARAMS_NUll);
        }

        Station stationInfo = enterpriseService.selectStationById(payOrderRequest.getStationId());
        if (Objects.isNull(stationInfo)) {
            return ResultData.error(CodeMsg.STATION_NULL_INFO);
        }

        OrderPayType orderPayType = orderPayTypeService.selectOrderPayTypeByPayType(payOrderRequest.getPayType());
        if (Objects.isNull(orderPayType)) {
            return ResultData.error("支付方式不存在");
        }
        log.info("/createCashOrderPayType请求参数：[{}}", JSONObject.toJSONString(payOrderRequest));


        if (StringUtils.isBlank(payOrderRequest.getUtmSource())) {
            // 订单来源默认9
            payOrderRequest.setUtmSource("9");
        }
        PayOrder payOrder = new PayOrder();
        payOrder.setPayType(payOrderRequest.getPayType());
        payOrder.setOrderOriginType(payOrderRequest.getOrderOriginType());  //订单来源
        payOrder.setOrderRandomId(payOrderRequest.getOrderRandomId());      //POS机随机号
        payOrder.setOilPersonnelId(payOrderRequest.getUserId());     //加油员ID
        payOrder.setStationName(stationInfo.getStationName());
        payOrder.setUtmSource(payOrderRequest.getUtmSource());
        payOrder.setAppType(payOrderRequest.getAppType());
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        payOrder.setOrderNo(ordNo);                                             //订单号
        logger.info("生成的订单号：" + ordNo);

        payOrder.setStationId(payOrderRequest.getStationId());
        payOrder.setEnterpriseId(stationInfo.getEnterpriseId());
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(stationInfo.getEnterpriseId());
        payOrder.setEnterpriseName(Objects.nonNull(enterprise) ? enterprise.getEnterpriseName() : null);
        //油站id
        payOrder.setCreatedDate(new Timestamp(new Date().getTime()));

        payOrder.setOilGun(payOrderRequest.getGunName());                       //油枪号

        //油品价格
        StaOilGun staOilGun = new StaOilGun();
        staOilGun.setGunName(payOrderRequest.getGunName());
        staOilGun.setStationId(payOrderRequest.getStationId());
        StaOilGun staOilGunInfo = enterpriseService.selectStaGunInfo(staOilGun);
        BigDecimal oilStationPrice = staOilGunInfo.getOilStationPrice();
        String oilPrice = oilStationPrice.toString();                    //油站油品价格
        payOrder.setOilPirce(oilPrice);
        payOrder.setOrderType(staOilGunInfo.getOil().getOilClass());        //订单类型

        //油品名称
        payOrder.setOilName(staOilGunInfo.getOilId().toString());
        //实收金额
        payOrder.setAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
        //应收金额
        payOrder.setReceivableAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
        //优惠金额
        payOrder.setDiscountAmt(Double.valueOf("0.00"));
        //加油升数
        BigDecimal oilLiters = new BigDecimal(payOrderRequest.getReceivableAmt()).divide(new BigDecimal(oilPrice), 4, BigDecimal.ROUND_HALF_UP);
        payOrder.setOrderLiters(oilLiters.toString());
        payOrder.setReceivableAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));      //订单应收金额
        payOrder.setWxAmt(Double.valueOf(0));
        payOrder.setZfbAmt(Double.valueOf(0));
        payOrder.setDzkAmt(Double.valueOf(0));

        payOrder.setConsumeDiscountAmt(BigDecimal.ZERO);
        payOrder.setRechargeDiscountAmt(BigDecimal.ZERO);

        payOrder.setStatus("1");
        payOrder.setXjAmt(Double.valueOf(payOrderRequest.getReceivableAmt()));
        payOrder.setConsumer("线下支付");       //客户昵称
        payOrder.setPayDate(new Timestamp(new Date().getTime()));
        //将客户昵称存入用户手机号
        payOrder.setConsumer("线下用户");
        payOrder.setInvoiceStatus(3);
        payOrderMapper.insertSelective(payOrder);
//                gzhNewsTemplateService.feiePush(payOrder);
        PayOrder po = payOrderService.selectOrderInfoByOrdNo(payOrder.getOrderNo());
        po.setPayTypeName(orderPayType.getPayTypeName());
        if (po.getMobilePhone() == null) {
            po.setMobilePhone("--");
        }
        return ResultData.success(po);
    }

    @PostMapping(value = "createCashPayOrder")
    @ApiOperation(value = "新版现金支付创建订单接口", httpMethod = "POST")
    public ResultData<PayOrder> createCashPayOrder(@RequestBody PayOrderRequest payOrderRequest) {
        PayOrder payOrder = payOrderService.createCashPayOrder(payOrderRequest);
        if (payOrder != null) {
            String phone = payOrder.getCustomerPhone();
            String encryPhone = MobilePhoneUtil.encryPhone(phone);
            payOrder.setMobilePhone(encryPhone);
        }
        return ResultData.success(payOrder);
    }

    //更新议价金额
    @PostMapping(value = "updateBargainAmt")
    @ApiOperation(value = "更新议价金额", httpMethod = "POST")
    @Transactional
    public ResultData updateBargainAmt(@RequestBody PayOrder payOrder){
        if (payOrder.getBargainAmt() == null){
            payOrder.setBargainAmt(BigDecimal.ZERO);
        }
        if (payOrder.getReceivableAmt() == null){
            payOrder.setReceivableAmt((double) 0);
        }
        BigDecimal subtract = BigDecimal.valueOf(payOrder.getReceivableAmt())
                .subtract(payOrder.getBargainAmt());
        log.info("更新议价金额 updateBargainAmt:[{}],subtract:[{}]",JSONObject.toJSONString(payOrder),subtract);
        //计算议价的价格
        payOrder.setBargainDiscountAmt(subtract);
        payOrderService.updateBargainAmt(payOrder);
        Map<String,BigDecimal> map = new HashMap<>();
        map.put("count",subtract);
        return ResultData.success(map);
    }

}
